【问题标题】:Execute curl command within Python在 Python 中执行 curl 命令
【发布时间】:2016-03-11 18:56:14
【问题描述】:

我是 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 库。

如何运行这个命令?

【问题讨论】:

  • StackOverflow 不是 cURL 到 Python requests 的转换服务。 curl.trillworks.com 是。
  • 你有理由使用curl,而不是仅仅从 Python 内部发送 HTTP 请求吗?

标签: python curl urllib2 bottle


【解决方案1】:

试试这个

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 代替。

【讨论】:

    【解决方案2】:

    您可以将 subprocess 与 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'])
    

    【讨论】:

      【解决方案3】:

      我不建议从 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

      【讨论】:

      • [文件 "C:\Python27\lib\httplib.py",第 732 行,在 _set_hostport raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) InvalidURL : nonnumeric port: '//hawkularmetrics.apps.10.2.2.2.xip.io/hawkular/metrics/metrics'] 我现在遇到了这个问题。
      【解决方案4】:

      您可以使用pycurl 库。

      pip install pycurl
      

      说明和例子here

      【讨论】:

        猜你喜欢
        • 2014-11-17
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 2016-06-22
        • 2019-08-13
        相关资源
        最近更新 更多