为什么这个来自python的bash调用不起作用?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了为什么这个来自python的bash调用不起作用?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2352字,纯文字阅读大概需要4分钟。
内容图文
我有点乱用比特币.当我想获得有关本地比特币安装的一些信息时,我只是运行比特币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.
内容总结
以上是互联网集市为您收集整理的为什么这个来自python的bash调用不起作用?全部内容,希望文章能够帮你解决为什么这个来自python的bash调用不起作用?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。