在Python脚本中执行curl命令

2024-06-16 11:48:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python脚本中执行curl命令。

如果我在终端上这样做,它看起来像这样:

curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001

我已经看到使用pycurl的建议,但我不知道如何将其应用到我的。

我试着用:

subprocess.call([
    'curl',
    '-X',
    'POST',
    '-d',
    flow_x,
    'http://localhost:8080/firewall/rules/0000000000000001'
])

而且有效,但是有更好的方法吗?


Tags: 命令src脚本actionslocalhosthttp终端curl
3条回答

别这样!

我知道,这是没人想要的“答案”。但如果有值得做的事,值得做对的事,对吧?

这似乎是一个好主意,可能源于一个相当广泛的误解,即诸如curl之类的shell命令不是程序本身。

所以你要问的是“我如何从我的程序中运行另一个程序,仅仅是为了发出一个微不足道的web请求?”。太疯狂了,一定有更好的办法,对吧?

Uxio's answer当然可以。但它看起来很难像是Python,不是吗?仅仅为了一个小小的请求就要做很多工作。Python应该是flying!任何一个写这篇文章的人都可能希望他们只是calldcurl


it works, but is there a better way?

是的,有一个更好的方法!

Requests: HTTP for Humans

Things shouldn’t be this way. Not in Python.

让我们看看这一页:

import requests
res = requests.get('https://stackoverflow.com/questions/26000336')

就这样,真的!然后就有了原始的res.text,或者res.json()输出,还有res.headers等等

你可以查看文档(链接在上面)了解设置所有选项的详细信息,因为我想OP现在已经开始了,而你——现在的读者——可能需要不同的选项。

但是,举个例子,它很简单:

url     = 'http://example.tld'
payload = { 'key' : 'val' }
headers = {}
res = requests.post(url, data=payload, headers=headers)

您甚至可以使用一个漂亮的Python dict在带有params={}的GET请求中提供查询字符串。

古朴典雅。保持冷静,继续飞行。

你可以像@roippi说的那样使用urllib:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

如果对curl命令的调整不太多,也可以直接调用curl命令

import shlex
cmd = '''curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

相关问题 更多 >