在虚拟环境下,执行某些命令需要有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: ~/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.

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐