在 Python 脚本中执行 curl 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26000336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:55:55  来源:igfitidea点击:

Execute curl command within a Python script

pythoncurlpycurl

提问by Kiran Vemuri

I am trying to execute a curl command within a python script.

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

If I do it in the terminal, it looks like this:

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

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

I've seen recommendations to use pycurl, but I couldn't figure out how to apply it to mine.

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

I tried using:

我尝试使用:

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

and it works, but is there a better way?

它有效,但有更好的方法吗?

采纳答案by Uxio

You could use urllib as @roippi said:

你可以像@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()

回答by hyades

If you are not tweaking the curl command too much you can also go and call the curl command directly

如果你没有过多地调整 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()

回答by OJFord

Don't!

别!

I know, that's the "answer" nobody wants. But if something's worth doing, it's worth doing right, right?

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

This seeming like a good idea probably stems from a fairly wide misconception that shell commands such as curlare anything other than programs themselves.

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

So what you're asking is "how do I run this other program, from within my program, just to make a measly little web request?". That's crazy, there's got to be a better way right?

所以你要问的是“我如何从我的程序中运行这个其他程序,只是为了发出一个微不足道的网络请求?”。这太疯狂了,一定有更好的方法吧?

Uxio's answerworks, sure. But it hardly looks very Pythonic, does it? That's a lot of work just for one little request. Python's supposed to be about flying! Anyone writing that is probably wishing they just call'd curl!

Uxio 的答案当然有效。但它看起来很难像Pythonic,是吗?仅仅为了一个小小的要求,就需要大量的工作。Python 应该是关于飞行的!任何写作的人可能都希望他们只是call'd curl



it works, but is there a better way?

它有效,但有更好的方法吗?

Yes, there isa better way!

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

Requests: HTTP for Humans

请求:HTTP for Humans

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

事情不应该这样。不是在 Python 中。

Let's GET this page:

让我们获取这个页面:

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

That's it, really! You then have the raw res.text, or res.json()output, the res.headers, etc.

就是这样,真的!然后res.text,您将获得原始或res.json()输出res.headers、 等。

You can see the docs (linked above) for details of setting all the options, since I imagine OP has moved on by now, and you - the reader now - likely need different ones.

您可以查看文档(上面链接)以获取有关设置所有选项的详细信息,因为我认为 OP 现在已经开始发展,而您 - 现在的读者 - 可能需要不同的选项。

But, for example, it's as simple as:

但是,例如,它很简单:

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

You can even use a nice Python dict to supply the query string in a GET request with params={}.

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

Simple and elegant. Keep calm, and fly on.

简单而优雅。保持冷静,继续飞行。

回答by Ganesh prasad

Rephrasing one of the answers in this post, instead of using cmd.split(). Try to use:

改写本文中的一个答案,而不是使用 cmd.split()。尝试使用:

import shlex

args = shlex.split(cmd)

Then feed args to subprocess.Popen.

然后将 args 提供给 subprocess.Popen。

Check this doc for more info: https://docs.python.org/2/library/subprocess.html#popen-constructor

查看此文档了解更多信息:https: //docs.python.org/2/library/subprocess.html#popen-constructor

回答by Nitin Nain

Use this tool(hosted herefor free) to convert your curl command to equivalent Python requests code:

使用此工具此处免费托管)将您的 curl 命令转换为等效的 Python 请求代码:

Example: This,

例子:这个,

curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --compressed

Gets converted neatly to:

整齐地转换为:

import requests

cookies = {
    'SESSID': 'ABCDEF',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Origin': 'https://www.example.com',
    'Accept-Encoding': 'gzip, deflate, br',
}

data = 'Pathfinder'

response = requests.post('https://www.example.com/', headers=headers, cookies=cookies, data=data)

回答by Ramesh Ponnusamy

Try with subprocess

尝试使用子流程

CurlUrl="curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache- 
          Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: 
          gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' -- 
          compressed"

Use getstatusoutputto store the results

使用getstatusoutput存储结果

status, output = subprocess.getstatusoutput(CurlUrl)