在 python 中执行 curl 命令

execute curl command in python

我已经通过几个 Whosebug 现有链接来查询此查询,但对我没有帮助。

我想 运行 几个 curl 命令(4) 并且每个 curl 命令都给出输出。从该输出中,我想为下一个命令解析几个组 ID。

curl --basic -u admin:admin -d \'{ "name" : "test-dev" }\' --header \'Content-Type: application/json\' http://localhost:8080/mmc/api/serverGroups

我试过 as ,

#!/usr/bin/python

import subprocess
bash_com = 'curl --basic -u admin:admin -d '{ "name" : "test-dev" }' --header 'Content-Type: application/json' http://localhost:8080/mmc/api/serverGroups'
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com]) # subprocess has check_output method

尽管我已将该 curl 命令从单引号更改为双引号,但它给我语法错误。

我一直在尝试使用 Pycurl,但我必须对其进行更多研究。有什么方法可以 运行 在 python 中执行 curl 命令并解析输出值并将其传递给下一个 curl 命令。

您可以将 os.popen 与

一起使用
fh = os.popen(bash_com, 'r')
data = fh.read()
fh.close()

或者你可以像这样使用子流程

cmds = ['ls', '-l', ]

try:
    output = subprocess.check_output(cmds, stderr=subprocess.STDOUT)
    retcode = 0
except subprocess.CalledProcessError, e:
    retcode = e.returncode
    output = e.output

print output

你必须在一个列表中组织你的命令和参数。

或者您只需使用简单的方法并使用 requests.get(...)。

并且不要忘记: 使用 popen 您可以通过命令参数进行 shell 注入!

更好的输出使用 os.open(bash_com,'r') 然后 fh.read()

python api.py

% Total % Received % Xferd Average Speed Time Time Time 电流 Dload Upload Total Spent Left 速度 199 172 0 172 0 27 3948 619 --:--:-- --:--:-- --:--:-- 4027 {"href":"http://localhost:8080/mmc/api/serverGroups/39a28908-3fae-4903-adb5-06a3b7bb06d8","serverCount":0,"name":"test-dev","id":"39a28908-3fae -4903-adb5-06a3b7bb06d8"}

试图理解 fh.read() 已经执行了 curl 命令?请指正

我正在尝试将 curl 命令输出重定向到文本文件,然后通过 JSON 解析该文件。我试图从输出中得到 "id"。

fh = os.popen(bash_com,'r')
data = fh.read()

newf = open("/var/tmp/t1.txt",'w')
sys.stdout = newf
print data

with open("/var/tmp/t1.txt") as json_data:
    j = json.load(json_data)
    print j['id']

我已经检查了 JSONlint.com 中的文件内容并得到了 VALID JSON。它在 json.load 行抛出 "ValueError: No JSON object could be decoded"。在解析重定向文件之前是否需要执行任何操作。