在我的本地机器上,我运行一个包含这一行的python脚本
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
os.system(bashCommand)
这很好。
然后在服务器上运行相同的代码,得到以下错误消息
'import site' failed; use -v for traceback
Traceback (most recent call last):
File "/usr/bin/cwm", line 48, in <module>
from swap import diag
ImportError: No module named swap
因此,我所做的是,我插入了一个打印bashCommand,它在终端中使用os.system()运行命令之前,将我打印出来。
当然,我再次得到错误(由os.system(bashCommand)引起),但在该错误之前,它在终端中打印命令。然后我复制输出并复制粘贴到终端,然后按enter,它工作了…
有人知道这是怎么回事吗?
python的方法是使用subprocess。Popen
子流程。Popen接受一个列表,其中第一个元素是要运行的命令,后面跟着任何命令行参数。
举个例子:
import subprocess
args = ['echo', 'Hello!']
subprocess.Popen(args) // same as running `echo Hello!` on cmd line
args2 = ['echo', '-v', '"Hello Again"']
subprocess.Popen(args2) // same as running 'echo -v "Hello Again!"` on cmd line
要在没有shell的情况下运行命令,将命令作为列表传递,并在Python中使用[subprocess]实现重定向:
#!/usr/bin/env python
import subprocess
with open('test.nt', 'wb', 0) as file:
subprocess.check_call("cwm --rdf test.rdf --ntriples".split(),
stdout=file)
注意:没有>测试。Nt在最后。文件实现重定向。
要在Python中使用shell运行命令,将命令作为字符串传递,并启用shell=True:
#!/usr/bin/env python
import subprocess
subprocess.check_call("cwm --rdf test.rdf --ntriples > test.nt",
shell=True)
这里是shell负责输出重定向(>测试。Nt在命令中)。
要运行使用bashisms的bash命令,需要显式指定bash可执行文件,例如,模拟bash进程替换:
#!/usr/bin/env python
import subprocess
subprocess.check_call('program <(command) <(another-command)',
shell=True, executable='/bin/bash')