我有点乱用比特币.当我想获得有关本地比特币安装的一些信息时,我只是运行比特币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" : ""
}
我现在想在Python内部做这个调用(在任何人指出之前;我知道有Python implementations for Bitcoin,我只想学习自己做).所以我首先尝试执行这样一个简单的ls命令:
import subprocess
process = subprocess.Popen('ls', stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
这工作正常,按预期打印出文件和文件夹列表.那么我这样做了:
import subprocess
process = subprocess.Popen('bitcoin getinfo', stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
但是这会产生以下错误:
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
在这里,我有点失落.有人知道这里有什么问题吗?欢迎所有提示!
[编辑]
使用下面的优秀答案,我现在做了以下功能,这对其他人也可能派上用场.它接受一个字符串,或带有单独参数的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
解决方法:
在参数中使用序列:
process = subprocess.Popen(['bitcoin', 'getinfo'], stdout=subprocess.PIPE)
或者将shell参数设置为True:
process = subprocess.Popen('bitcoin getinfo', stdout=subprocess.PIPE, shell=True)
您可以在documentation中找到更多信息:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.