[英]Curl issue in subprocess Python
When I tried to run the following command on the command line, I get the storage size. 当我尝试在命令行上运行以下命令时,我得到了存储大小。
curl -G -d "key=val" 'http://172.16.26.2:9005/as/system/storage'
{
"userQuotaMax" : 675048,
"userQuotaUsed" : 439191
}
If I try to run in my python script, Then, I can'not get the same data. 如果尝试在python脚本中运行,则无法获得相同的数据。
arg_list = curl -G -d "key=val" 'http://172.16.26.2:9005/as/system/storage'
p = Popen(arg_list, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, executable='/bin/bash')
output = p.stdout.read()
print output
Any helps would be really appreciated. 任何帮助将不胜感激。
Instead of calling curl using popen(), you might be better served by using requests. 与其使用popen()调用curl,不如使用请求来更好地服务。
http://docs.python-requests.org/en/master/user/quickstart/ http://docs.python-requests.org/en/master/user/quickstart/
so something like (for GET): 所以像(对于GET):
import requests
payload = {"key" :"val"}
response = requests.get("http://172.16.26.2:9005/as/system/storage", data=payload)
print(response.text)
so something like (for POST): 所以像(对于POST):
import requests
payload = {"key" :"val"}
response = requests.post("http://172.16.26.2:9005/as/system/storage", data=payload)
print(response.text)
Should return (assuming the api returns html/text, if it returns JSON, have a look at response.json() explained at the link above): 应该返回(假设api返回html / text,如果返回JSON,请查看上面链接中解释的response.json()):
{
"userQuotaMax" : 675048,
"userQuotaUsed" : 439191
}
Hope this helps you 希望这对您有帮助
My first guess is you have issues with quoting. 我的第一个猜测是您在报价方面遇到问题。 Try this instead: 尝试以下方法:
arg_list = ['/usr/bin/curl', '-G', '-d', 'key=val', 'http://172.16.26.2:9005/as/system/storage']
p = Popen(arg_list, shell=False, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
import pycurl
from StringIO import StringIO
data_size = StringIO()
curl_command = pycurl.Curl()
curl_command.setopt(curl_command.URL, 'http://{}:9005/as/system/storage'.format(ip))
curl_command.setopt(curl_command.WRITEDATA, data_size)
curl_command.perform()
curl_command.close()
output = data_size.getvalue()
This is also another solution with pycurl module. 这也是pycurl模块的另一个解决方案。 But, I think requests is better one :) 但是,我认为要求更好:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.