1. 程式人生 > >Ubuntu下新增Python環境變數

Ubuntu下新增Python環境變數

最近把自己在windows上的Django專案放在的Ubuntu上,啟動時提示找不到模組

原來是自己的專案用的是虛擬環境,安裝的第三方庫全部在虛擬環境中 AutoTestSite/venv/Lib/site-packages

在Ubuntu中檢視模組搜尋路徑:

[email protected]:~$ python
Python 2.7.12 (default, Nov 12 2018, 14:36:49) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more
information. >>> import sys >>> sys.path ['', '/home/chen', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

發現並沒有這個路徑:AutoTestSite/venv/Lib/site-packages

所以需要新增路徑:

編輯檔案 sudo vi .bashrc ,在最下方新增:

export PYTHONPATH="/home/**/**/venv/Lib/site-packages:$PYTHONPATH"

 

[email protected]:~$ sudo vi .bashrc 

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don
't do anything case $- in *i*) ;; *) return;; esac # don't put duplicate lines or lines starting with space in the history. # See bash(1) for more options HISTCONTROL=ignoreboth # append to the history file, don't overwrite it shopt -s histappend # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=1000 HISTFILESIZE=2000 # check the window size after each command and, if necessary, # update the values of LINES and COLUMNS. shopt -s checkwinsize # If set, the pattern "**" used in a pathname expansion context will # match all files and zero or more directories and subdirectories. #shopt -s globstar # add python project autotestsite module search path assress export PYTHONPATH="/home/guchen/python/www/for_test/AutoTestSite/venv/Lib/site-packages:$PYTHONPATH"

執行:source .bashrc

使修改生效

再次檢視sys.path,已經添加了

[email protected]:~$ python
Python 2.7.12 (default, Nov 12 2018, 14:36:49) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/chen/python/www/AutoTestSite/venv/Lib/site-packages', '/home/chen', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']