在我的本地机器上,我运行一个包含这一行的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”的方式。所以我创建了Sultan(无耻的插头),它可以很容易地运行命令行函数。

https://github.com/aeroxis/sultan

其他回答

用subprocess调用它

import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")

你得到的错误似乎是因为服务器上没有交换模块,你应该在服务器上安装交换模块,然后再次运行脚本

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')

根据错误,您在服务器上丢失了一个名为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()