【发布时间】:2014-08-12 00:21:21
【问题描述】:
我有点玩弄比特币。当我想获取有关本地比特币安装的一些信息时,我只需运行 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" : ""
}
我现在想在 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
在这里我有点迷路了。有人知道这里有什么问题吗?欢迎所有提示!
[编辑] 使用下面的优秀答案,我现在制作了以下功能,这对其他人也可能派上用场。它接受一个字符串,或者一个带有单独参数的可迭代对象,如果它是 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
【问题讨论】:
-
你确定你的脚本真的能看到“比特币”可执行文件吗?如果它位于 /usr/bin 或同等位置,请尝试提供完整路径。
ls是一个 shell 命令,可以在任何地方访问,这就是它起作用的原因。
标签: python bash subprocess bitcoin