在 Python 内执行 curl 命令

Execute curl command within Python

我是 python 的初学者。我正在尝试在 Python 脚本中执行 curl 命令。

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

curl -k -H "Authorization: Bearer xxxxxxxxxxxxxxxx" -H "hawkular-tenant: test" -X GET https://www.example.com/test | python -m json.tool

我试着做研究,所以我想我可以使用 urllib2 库。

如何运行这个命令?

试试这个

import subprocess

bash_com = 'curl -k -H "Authorization: Bearer xxxxxxxxxxxxxxxx" -H "hawkular-tenant: test" -X GET https://www.example.com/test | python -m json.tool'
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])

这是一个很好的方法,因为它避免了使用 os.system,这会使事情变得难看。但是尽量避免从 Python 内部调用 bash 命令,特别是在这种情况下,您可以简单地使用 Requests 代替。

我不建议从 Python 内部通过您的 shell 调用 curlhttplib 呢?

import httplib
conn = httplib.HTTPConnection("https://www.example.com/test")
conn.request("HEAD","Authorization: Bearer xxxxxxxxxxxxxxxx")
conn.request("HEAD", "hawkular-tenant: test")
res = conn.getresponse()

如果您使用的是 Python3,那么您需要将 httplib 换成 http.client

您可以将子进程与 Popen 一起使用并进行通信以执行命令并检索输出。

def executeCommand(cmd, debug = False):
   '''
   Excecute a command and return the stdiout and errors.
   cmd: list of the command. e.g.: ['ls', '-la']
   '''
   try:
      cmd_data = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      output,error = cmd_data.communicate()
      if debug:
         if (len(error)>1):
            print 'Error:', error
         if (len(output)>1):
            print 'Output:', output
      return output, error
   except:
      return 'Error in command:', cmd

然后,你把你的命令写成

executeCommand(['curl', '-k', '-H', '"Authorization: Bearer xxxxxxxxxxxxxxxx"', '-H', '"hawkular-tenant: test"', '-X', 'GET', 'https://www.example.com/test', '|', 'python', '-m', 'json.tool'])

您可以使用 pycurl 库。

pip install pycurl

说明和示例here