使用subprocess.check_call()运行shell命令时出错

时间:2016-10-26 07:32:45

标签: python linux subprocess rpyc

# -*- coding: utf-8 -*-
import rpyc
conn = rpyc.classic.connect(r"xx.xx.xx.xx")
s = conn.modules.subprocess.check_output(['file',u'`which dd`'])
print s

输出是:

`which dd`: cannot open ``which dd`' (No such file or directory)  

Process finished with exit code 0

当我在命令提示符下手动执行时,它给出了正确的输出:

/bin/dd: symbolic link to /bin/dd.coreutils

我的代码中是否有任何Unicode错误

1 个答案:

答案 0 :(得分:0)

它在命令提示符下运行。但是,如果您通过subprocess调用它(因此将使用conn.modules.subprocess),它会给您错误:

>>> subprocess.check_call(['file', '`which python`'])
`which python`: cannot open ``which python`' (No such file or directory)

因为在shell中,这将执行:

 mquadri$ file '`which python`'
`which python`: cannot open ``which python`' (No such file or directory)

但你想把它当作:

mquadri$ file `which python`
/usr/bin/python: Mach-O universal binary with 2 architectures
/usr/bin/python (for architecture i386):    Mach-O executable i386
/usr/bin/python (for architecture x86_64):  Mach-O 64-bit executable x86_64

为了使上述命令运行,请将其作为字符串传递给check_callshell=True为:

>>> subprocess.check_call('file `which python`', shell=True)
/usr/bin/python: Mach-O universal binary with 2 architectures
/usr/bin/python (for architecture i386):    Mach-O executable i386
/usr/bin/python (for architecture x86_64):  Mach-O 64-bit executable x86_64