为什么这个来自python的bash调用不起作用?

kra*_*r65 3 python bash subprocess bitcoin

我有点乱用比特币.当我想获得有关本地比特币安装的一些信息时,我只是运行bitcoin getinfo,我得到这样的东西:

{
    "version" : 90100,
    "protocolversion" : 70002,
    "walletversion" : 60000,
    "balance" : 0.00767000,
    "blocks" : 306984,
    "timeoffset" : 0,
    "connections" : 61,
    "proxy" : "",
    "difficulty" : 13462580114.52533913,
    "testnet" : false,
    "keypoololdest" : 1394108331,
    "keypoolsize" : 101,
    "paytxfee" : 0.00000000,
    "errors" : ""
}
Run Code Online (Sandbox Code Playgroud)

我现在想要在Python内部进行此调用(在任何人指出之前;我知道有比特币的Python实现,我只是想学习自己做).所以我首先尝试执行这样一个简单的ls命令:

import subprocess
process = subprocess.Popen('ls', stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
Run Code Online (Sandbox Code Playgroud)

这工作正常,按预期打印出文件和文件夹列表.那么我这样做了:

import subprocess
process = subprocess.Popen('bitcoin getinfo', stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
Run Code Online (Sandbox Code Playgroud)

但是这会产生以下错误:

Traceback (most recent call last):
  File "testCommandLineCommands.py", line 2, in <module>
    process = subprocess.Popen('bitcoin getinfo', stdout=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)

在这里,我有点失落.有人知道这里有什么问题吗?欢迎所有提示!

[编辑]使用下面的优秀答案,我现在做了以下功能,这对其他人也可能派上用场.它接受一个字符串,或带有单独参数的iterable,如果它是json,则解析输出:

def doCommandLineCommand(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=isinstance(command, str))
    output = process.communicate()[0]
    try:
        return json.loads(output)
    except ValueError:
        return output
Run Code Online (Sandbox Code Playgroud)

Ger*_*osi 10

在参数中使用序列:

process = subprocess.Popen(['bitcoin', 'getinfo'], stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

或将shell参数设置为True:

process = subprocess.Popen('bitcoin getinfo', stdout=subprocess.PIPE, shell=True)
Run Code Online (Sandbox Code Playgroud)

您可以在文档中找到更多信息:

所有调用都需要args,并且应该是一个字符串或一系列程序参数.通常优选提供参数序列,因为它允许模块处理任何所需的转义和引用参数(例如,允许文件名中的空格).如果传递单个字符串,则shell必须为True(参见下文),否则字符串必须简单地命名要执行的程序而不指定任何参数.