前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >解决Python虚拟环境virtual

解决Python虚拟环境virtual

作者头像
py3study
发布2020-01-02 17:21:22
1K0
发布2020-01-02 17:21:22
举报
文章被收录于专栏:python3python3

 解决Python虚拟环境下不能使用sudo提升权限问题

问题描述

在虚拟环境下,执行某些命令需要有sudo提升权限,会导致该条命令退出虚拟环境:

如启动django 服务,需要监听80端口:

代码语言:javascript
复制
$: 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提升命令权限:

代码语言:javascript
复制
$: ~/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模块安装正常:

代码语言:javascript
复制
$: 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模块无法导入:

代码语言:javascript
复制
$: 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执行命令的时候,该命令会退出当前虚拟环境执行:

代码语言:javascript
复制
$: sudo which python
/usr/bin/python
$: which python
/home/hzc/python3env/venv/bin/python

解决办法

指定python路径

代码语言:javascript
复制
$: 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地址(局限于执行脚本)

代码语言:javascript
复制
#!/usr/bin/env python 更改前
#!/home/hzc/python3env/venv/bin/python 更改后

执行脚本:

代码语言:javascript
复制
$: 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.
 ​
 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  •  解决Python虚拟环境下不能使用sudo提升权限问题
    • 问题描述
      • 解决办法
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档