解决Python虚拟环境virtual

发布时间:2019-10-14 09:21:37编辑:auto阅读(2922)

     解决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.

关键字