如何在Python中运行上下文感知命令?

2024-06-02 17:03:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python编写一些python包安装脚本到virtualenv中。我编写了一个安装virtualenv的函数

def prepareRadioenv():
    if not os.path.exists('radioenv'):
        print 'Create radioenv'
        system('easy_install virtualenv')
        system('virtualenv --no-site-package radioenv')
    print 'Activate radioenv'
    system('source radioenv/bin/activate')

我试着用“source radioenv/bin/activate”激活虚拟环境,不幸的是,操作系统创建执行该命令的子进程。activate所做的环境更改随子进程而消失,不会影响Python进程。问题来了,如何在Python中执行上下文感知命令序列?在

另一个例子:

^{pr2}$

这里的cd不会影响下面的系统(“.bar”)。如何使这些环境上下文在不同的命令中生存?在

有没有类似上下文感知的shell?这样我就可以编写如下Python代码:

shell = ShellContext()
shell.system("cd bar")
shell.system("./configure")
shell.system("make install")
if os.path.exists('bar'):
    shell.system("remove")

谢谢。在


Tags: installpath命令sourceifvirtualenv进程os
2条回答

要从Python中激活virtualenv,请使用activate_this.py脚本(它是用virtualenv创建的)和execfile。在

activate_this = os.path.join("path/to/radioenv", "bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))

你想用Python作为shell?在

丹尼尔·罗斯曼的回答似乎是你所需要的最大的部分,同时请注意:

shell.system("cd bar")

在Python中拼写为:

^{pr2}$

检查os模块中的其他功能,如rmdirremove和{}。在

相关问题 更多 >