Ubuntu環境下Python遠程協作的常見實現方法
SSH(Secure Shell)是Ubuntu系統默認的安全遠程登錄協議,可實現命令行級別的遠程協作,適合快速執行Python腳本、管理服務器環境及傳輸文件。
sudo systemctl status ssh
檢查服務狀態,未安裝則運行sudo apt install openssh-server
;本地計算機需安裝SSH客戶端(Linux/macOS內置,Windows可使用PuTTY或WSL)。ssh username@remote_ip
(替換為遠程用戶名和IP地址),輸入密碼即可登錄遠程服務器。scp
命令實現本地與遠程服務器的文件同步,例如將本地script.py
上傳至遠程/home/user/
目錄,命令為scp /local/path/script.py username@remote_ip:/home/user/
。cd
命令切換至腳本所在目錄,執行python3 script.py
運行腳本;若使用虛擬環境,需先激活環境(source myenv/bin/activate
)再運行腳本。Jupyter Notebook支持多人實時編輯、共享內核及可視化輸出,適合數據科學、機器學習等需要交互式開發的場景。
wget https://repo.anaconda.com/archive/Anaconda3-2023.07-Linux-x86_64.sh && bash Anaconda3-2023.07-Linux-x86_64.sh -b
安裝,配置環境變量echo "export PATH=$HOME/anaconda3/bin:$PATH" >> ~/.bashrc && source ~/.bashrc
。sudo useradd -m jupyter_user && sudo passwd jupyter_user
),切換至該用戶,創建Python環境(conda create -n jupyter_env python=3.9 -y && conda activate jupyter_env
),安裝Jupyter(pip install jupyter notebook ipywidgets
),生成配置文件(jupyter notebook --generate-config
)。from notebook.auth import passwd; passwd()
),復制哈希值至配置文件(~/.jupyter/jupyter_notebook_config.py
),修改c.NotebookApp.password
、c.NotebookApp.ip='*'
(允許所有IP訪問)、c.NotebookApp.port=8899
(自定義端口)、c.NotebookApp.open_browser=False
(不自動打開瀏覽器)。sudo apt install nginx
),使用Let’s Encrypt獲取SSL證書(sudo apt install certbot python3-certbot-nginx && sudo certbot --nginx -d your-domain.com
),配置Nginx反向代理(新建/etc/nginx/sites-available/jupyter
文件,設置SSL證書路徑及代理轉發),啟用配置(sudo ln -s /etc/nginx/sites-available/jupyter /etc/nginx/sites-enabled/ && sudo nginx -t && sudo systemctl restart nginx
)。jupyter notebook
),通過https://your-domain.com:8899
訪問,輸入密碼即可實現多人實時協作。VNC(Virtual Network Computing)提供圖形化遠程桌面,適合需要可視化界面(如PyCharm、Matplotlib繪圖)的協作場景。
sudo apt install tigervnc-standalone-server
),啟動配置向導(vncserver :1
),設置訪問密碼(用于遠程連接)。~/.vnc/xstartup
文件,添加gnome-session &
(啟動GNOME桌面)或startxfce4 &
(啟動XFCE桌面,更輕量),保存后重啟VNC Server(vncserver -kill :1 && vncserver :1
)。vncserver :1
啟動服務,默認端口為5901
(:1
對應5901,:2
對應5902),可通過netstat -tulnp | grep 5901
檢查端口狀態。remote_ip:5901
),連接后輸入密碼即可查看遠程桌面,通過桌面環境運行Python程序(如通過PyCharm編輯代碼)。ssh -L 5901:localhost:5901 username@remote_ip
,然后本地連接localhost:5901
。版本控制是團隊協作的基礎,結合CI/CD(持續集成/持續部署)可實現代碼自動測試與部署,適合大型項目。
sudo apt install git
),配置用戶名與郵箱(git config --global user.name "Your Name"
、git config --global user.email "your.email@example.com"
),初始化本地倉庫(git init
),添加遠程倉庫(git remote add origin https://github.com/username/repo.git
),推送代碼(git push -u origin main
)。pytest
)、安裝依賴(pip install -r requirements.txt
),確保代碼質量。配置文件如.github/workflows/python-app.yml
(GitHub Actions),內容示例:name: Python CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: pytest
這種方法適合團隊協作,確保代碼一致性,減少集成問題,提高開發效率。