使用Python脚本激活virtualenv

发布于 2021-02-02 23:12:37

我想从Python脚本激活virtualenv实例。

我知道这很容易做到,但是我看过的所有示例都使用它在env中运行命令,然后关闭子进程。

我只是想激活virtualenv并返回外壳,就像bin / activate一样。

像这样:

$me: my-script.py -d env-name
$(env-name)me:

这可能吗?

关注者
0
被浏览
68
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    如果要在virtualenv下运行Python子进程,可以通过使用位于virtualenv/ bin /目录中的Python解释器运行脚本来实现:

    # Path to a Python interpreter that runs any Python script
    # under the virtualenv /path/to/virtualenv/
    python_bin = "/path/to/virtualenv/bin/python"
    
    # Path to the script that must run under the virtualenv
    script_file = "must/run/under/virtualenv/script.py"
    
    subprocess.Popen([python_bin, script_file])
    

    但是,如果要在当前的Python解释器下而不是子进程下激活virtualenv,则可以使用以下activate_this.py脚本:

    # Doing execfile() on this file will alter the current interpreter's
    # environment so you can import libraries in the virtualenv
    activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
    
    execfile(activate_this_file, dict(__file__=activate_this_file))
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看