如何在Python中运行上下文感知命令?
我想写一个用Python编写的脚本,用来安装一些Python包到虚拟环境中。我写了一个函数来安装虚拟环境。
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”来激活虚拟环境,但不幸的是,os.system会创建一个子进程来执行这个命令。这样一来,激活后环境的变化就只在子进程中有效,主程序的Python环境并没有受到影响。这就出现了问题,我该如何在Python中执行一些能感知环境的命令序列呢?
另一个例子:
system("cd foo")
system("./bar")
在这里,cd命令并不会影响后面的system(".bar")。我该如何让这些环境上下文在不同的命令中保持有效呢?
有没有类似于能感知上下文的shell?这样我就可以写一些像这样的Python代码:
shell = ShellContext()
shell.system("cd bar")
shell.system("./configure")
shell.system("make install")
if os.path.exists('bar'):
shell.system("remove")
谢谢。
2 个回答
1
你想用Python当命令行工具吗?
和Daniel Roseman的回答一样,这里有一些你需要注意的内容:
shell.system("cd bar")
在Python中写成:
os.chdir("bar")
你可以查看os模块,里面还有其他你可能需要的功能,比如rmdir
(删除目录)、remove
(删除文件)和mkdir
(创建目录)。
3
要在Python中激活虚拟环境,可以使用一个叫做 activate_this.py
的脚本(这个脚本是创建虚拟环境时生成的),然后用 execfile
来执行它。
activate_this = os.path.join("path/to/radioenv", "bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))