在我的本地机器上,我运行一个包含这一行的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,它工作了…

有人知道这是怎么回事吗?


当前回答

要在没有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')

其他回答

要在没有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')

你可以使用bash程序,带参数-c来执行命令:

bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
output = subprocess.check_output(['bash','-c', bashCommand])

你也可以使用'os.popen'。 例子:

import os

command = os.popen('ls -al')
print(command.read())
print(command.close())

输出:

total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root   77 ago 13 21:53 test.py

None

根据错误,您在服务器上丢失了一个名为swap的包。这个/usr/bin/cwm需要它。如果你使用的是Ubuntu/Debian,使用aptitude安装python-swap。

不要使用os.system。它已被弃用,而支持subprocess。文档中写道:“这个模块打算取代几个旧的模块和函数:os。系统,os.spawn”。

比如你的例子:

import subprocess

bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()