pycharm配置远程解释器开发
在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,连接到远程服务器,执行
1 | pip3 install -r requirements.txt |
即可。
二、SSH连接Docker容器内部的解释器
这种方式仍然是通过SSH连接,只不过需要连接到Docker容器内部。
缺点:需要在容器中安装启动sshd,存在开销和攻击面增大的问题,同时也违反了Docker所倡导 的一个容器一个进程的原则:容器本身是一个无状态,用后即焚的东西。容器一般只有一个进程,否则容器会越来越大,越来越像一个虚拟机一样笨重不宜维护。
步骤如下:
首先创建容器,通过暴露容器服务端口,把宿主机上10086(空闲端口)映射到容器内22端口,并且配置数据卷挂载:
1 | docker run -di --name python36 -p 10086:22 -v /root/data:/opt/data python:3.6 |
进入容器
1 | docker exec -it python36 /bin/bash |
容器内安装SSH服务和必要工具:
1 | yum install passwd openssl openssh-server openssh-clients -y |
如果没有yum命令,则说明这个容器的基础镜像不是centos。
要知道你使用的基础是镜像是什么版本,使用如下命令:
1
2
3
4
5 cat /etc/issue
Debian GNU/Linux 11 \n \l
# 如果是centos肯定有yum
# 如果是debian/ubuntu则是apt-get
# 如果是alpine则是apk这里查询是debian,所以没有yum。
1
2 apt-get install vim # 安装vim
vim /etc/apt/sources.list # 修改安装源这里给出Debian 11在国内的镜像源
1
2
3
4
5
6
7
8 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更新索引
1 apt-get update之后再次安装:
1 apt-get install passwd openssl openssh-server openssh-client -y
修改root密码:
1 | passwd root |
修改配置vim /etc/ssh/sshd_config 修改如下内容:
1 | PubkeyAuthentication yes #启用公钥私钥配对认证方式 |
启动ssh服务
1 | service ssh start |
现在就可以通过10086端口远程连接到此docker容器了。
下面配置pycharm解释器:



配置完成后,运行测试文件:

在宿主机上查看数据卷挂载情况:

如果需要安装第三方模块,也可以通过编写requirements.txt后,连接到容器:

进入容器后,到数据卷挂载目录下安装即可:
1 | cd /opt/data/ |