解決Python虛擬環境virtualenv下不能使用sudo提升許可權問題

hzcyf發表於2019-02-16

 解決Python虛擬環境下不能使用sudo提升許可權問題

問題描述

在虛擬環境下,執行某些命令需要有sudo提升許可權,會導致該條命令退出虛擬環境:

如啟動django 服務,需要監聽80埠:

$: 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埠。

所以通過sudo提升命令許可權:

$: ~/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模組安裝正常:

$: 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模組無法匯入:

$: 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執行命令的時候,該命令會退出當前虛擬環境執行:

$: sudo which python
/usr/bin/python
$: which python
/home/hzc/python3env/venv/bin/python

解決辦法

  1. 指定python路徑

    $: 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.
    
  2. 在指令碼中指定python地址(侷限於執行指令碼)

    #!/usr/bin/env python 更改前
    #!/home/hzc/python3env/venv/bin/python 更改後

    執行指令碼:

    $: 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.

相關文章