在虛擬環境下,執行某些命令須要有sudo提高權限,會致使該條命令退出虛擬環境:python
如啓動django 服務,須要監聽80端口:linux
$: python manage.py runserver 80 Performing system checks... System check identified no issues (0 silenced). March 15, 2018 - 07:43:40 Django version 2.0.3, using settings 'helloworld.settings' Starting development server at http://127.0.0.1:80/ Quit the server with CONTROL-C. Error: You don't have permission to access that port.
此時會提示權限不足,沒法訪問80端口。shell
因此經過sudo提高命令權限:django
$: ~/python3env/helloworld$ sudo python manage.py runserver 80 Traceback (most recent call last): File "manage.py", line 11, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
此時會提示沒有找到Django
模塊,但是通過以下驗證,Django
模塊安裝正常:ide
$: python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.__version__ '2.0.3'
而使用sudo啓動python,會發現,Django
模塊沒法導入:ui
$: sudo python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named django
原來,在使用sudo執行命令的時候,該命令會退出當前虛擬環境執行:code
$: sudo which python /usr/bin/python $: which python /home/hzc/python3env/venv/bin/python
指定python路徑orm
$: sudo ../venv/bin/python manage.py runserver 80 Performing system checks... System check identified no issues (0 silenced). March 15, 2018 - 07:55:29 Django version 2.0.3, using settings 'helloworld.settings' Starting development server at http://127.0.0.1:80/ Quit the server with CONTROL-C.
在腳本中指定python地址(侷限於執行腳本)server
#!/usr/bin/env python 更改前 #!/home/hzc/python3env/venv/bin/python 更改後
執行腳本:get
$: sudo ./manage.py runserver 80 Performing system checks... System check identified no issues (0 silenced). March 15, 2018 - 08:02:48 Django version 2.0.3, using settings 'helloworld.settings' Starting development server at http://127.0.0.1:80/ Quit the server with CONTROL-C.