解决Python虚拟环境virtualenv下不能使用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提升命令权限:

:   / p y t h o n 3 e n v / h e l l o w o r l d : ~/python3env/helloworld : /python3env/helloworld sudo python manage.py runserver 80
Traceback (most recent call last):
File “manage.py”, line 11, in
"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 “”, line 1, in
ImportError: No module named django
原来,在使用sudo执行命令的时候,该命令会退出当前虚拟环境执行:

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

解决办法
指定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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值