在windows上開發python,經常會遇到第三方庫無法安裝的情況,比如lxml,scrapy,celery,twisted等,有些可以通過手動安裝wheel文件來解決(wheel文件下載地址),有些根本無法安裝,遇到這樣的問題,解決方案如下:
- 換電腦:最簡單的方法,換成linux或者mac
- 在windows電腦安裝ubuntu虛擬機,在虛擬機中開發
- 配置遠程解釋器,仍然在本地windows開發,使用遠程linux的解釋器運行
本文介紹的就是第三種方法。
pycharm提供了多種方式配置遠程解釋器,下面分別介紹。
一、配置SSH解釋器
步驟如下:
打開pycharm-->左上角settings-->Python Interpreter-->小齒輪-->Add..
如果勾選了Automatically upload project files to the server
,你本地的代碼會自動上傳到遠程服務器,無需手動上傳。
接下來運行代碼測試一下:
如果需要安裝第三方模塊,可以通過編寫requirements.txt
,連接到遠程服務器,執行
pip3 install -r requirements.txt
即可。
二、SSH連接Docker容器內部的解釋器
這種方式仍然是通過SSH連接,只不過需要連接到Docker容器內部。
缺點:需要在容器中安裝啟動sshd,存在開銷和攻擊面增大的問題,同時也違反了Docker所倡導 的一個容器一個進程的原則:容器本身是一個無狀態,用后即焚的東西。容器一般只有一個進程,否則容器會越來越大,越來越像一個虛擬機一樣笨重不宜維護。
步驟如下:
首先創建容器,通過暴露容器服務端口,把宿主機上10086(空閑端口)映射到容器內22端口,並且配置數據卷掛載:
docker run -di --name python36 -p 10086:22 -v /root/data:/opt/data python:3.6
進入容器
docker exec -it python36 /bin/bash
容器內安裝SSH服務和必要工具:
yum install passwd openssl openssh-server openssh-clients -y
如果沒有yum命令,則說明這個容器的基礎鏡像不是centos。
要知道你使用的基礎是鏡像是什么版本,使用如下命令:
cat /etc/issue Debian GNU/Linux 11 \n \l # 如果是centos肯定有yum # 如果是debian/ubuntu則是apt-get # 如果是alpine則是apk
這里查詢是debian,所以沒有yum。
apt-get install vim # 安裝vim vim /etc/apt/sources.list # 修改安裝源
這里給出Debian 11在國內的鏡像源
deb https://mirrors.aliyun.com/debian/ bullseye main non-free contrib deb-src https://mirrors.aliyun.com/debian/ bullseye main non-free contrib deb https://mirrors.aliyun.com/debian-security/ bullseye-security main deb-src https://mirrors.aliyun.com/debian-security/ bullseye-security main deb https://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib deb-src https://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib deb https://mirrors.aliyun.com/debian/ bullseye-backports main non-free contrib deb-src https://mirrors.aliyun.com/debian/ bullseye-backports main non-free contrib
更新索引
apt-get update
之后再次安裝:
apt-get install passwd openssl openssh-server openssh-client -y
修改root密碼:
passwd root
修改配置vim /etc/ssh/sshd_config
修改如下內容:
PubkeyAuthentication yes #啟用公鑰私鑰配對認證方式
AuthorizedKeysFile .ssh/authorized_keys #公鑰文件路徑
PermitRootLogin yes #root能使用ssh登錄
啟動ssh服務
service ssh start
現在就可以通過10086端口遠程連接到此docker容器了。
下面配置pycharm解釋器:
配置完成后,運行測試文件:
在宿主機上查看數據卷掛載情況:
如果需要安裝第三方模塊,也可以通過編寫requirements.txt
后,連接到容器:
進入容器后,到數據卷掛載目錄下安裝即可:
cd /opt/data/
pip3 install -r requirements.txt