Curl issue in subprocess Python

2019-08-06 18:50发布

问题:

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.

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.

回答1:

Instead of calling curl using popen(), you might be better served by using requests.

http://docs.python-requests.org/en/master/user/quickstart/


so something like (for 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):

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):

{
   "userQuotaMax" : 675048,
   "userQuotaUsed" : 439191
}

Hope this helps you



回答2:

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)


回答3:

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. But, I think requests is better one :)