假设我在 Python 中有一个看起来像这样的命令
command = 'curl ...etc" > result.json'
subprocess.call(command, shell = True)
file = open("result.json").read()
它现在所做的是从我 curl 的地方获取并将结果存储在 result.json 中,然后我打开它来读取它。有什么办法不用先存到本地就可以直接读取?
请您参考如下方法:
您可以使用标准库 ( json & urllib2 ) 来避免使用外部命令:
import json
import urllib2
url = "http://httpbin.org/get"
response = urllib2.urlopen(url)
data = response.read()
values = json.loads(data)
但我建议使用 requests来简化你的代码。这是来自文档的示例:
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
200
r.headers['content-type']
'application/json; charset=utf8'
r.encoding
'utf-8'
r.text
u'{"type":"User"...'
r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
Python 3 更新
请考虑在 Python3 中 urllib2 不再存在,您应该使用 urllib标准库中的
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
data = response.read()
values = json.loads(data)