【问题标题】:How to use Python to execute a cURL command?如何使用 Python 执行 cURL 命令?
【发布时间】:2014-10-18 21:49:27
【问题描述】:

我想在 Python 中执行 curl 命令。

通常,我只需要在终端中输入命令并按回车键即可。但是,我不知道它在 Python 中是如何工作的。

命令如下:

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

要发送一个request.json 文件以获得响应。

我搜索了很多并感到困惑。我试着写了一段代码,虽然我不能完全理解,也没有成功。

import pycurl
import StringIO

response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '@request.json')
c.perform()
c.close()
print response.getvalue()
response.close()

错误消息是Parse Error。如何正确获取服务器的响应?

【问题讨论】:

标签: python curl


【解决方案1】:

如果你的操作系统支持 curl,你可以这样做:

import os

os.system("curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere")

我正在使用这种方式...而且我认为您也可以使用它!

顺便说一句.. 安装 python 时,模块“os”会自动安装。 所以,你不需要安装包;)

【讨论】:

    【解决方案2】:

    Python 3

    仅适用于 UNIX (Linux / Mac) (!)

    使用 Python 3 执行 cURL 并解析其 JSON 数据。

    import shlex
    import json
    import subprocess
    
    # Make sure that cURL has Silent mode (--silent) activated
    # otherwise we receive progress data inside err message later
    cURL = r"""curl -X --silent POST http://www.test.testtestest/ -d 'username=test'"""
    
    lCmd = shlex.split(cURL) # Splits cURL into an array
    
    p = subprocess.Popen(lCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate() # Get the output and the err message
    
    json_data = json.loads(out.decode("utf-8"))
    
    print(json_data) # Display now the data
    

    如果遇到奇怪的错误,有时您还需要在 UNIX 上安装这些依赖项:

    # Dependencies  
    sudo apt install libcurl4-openssl-dev libssl-dev
    sudo apt install curl
    

    【讨论】:

      【解决方案3】:

      我使用os 库。

      import os
      
      os.system("sh script.sh")
      

      script.sh 实际上只包含 curl。

      【讨论】:

        【解决方案4】:

        一些背景知识:我一直在寻找这个问题,因为我必须做一些事情来检索内容,但我所拥有的只是一个旧版本的 python,它的 SSL 支持不足。如果您使用的是较旧的 MacBook,您就会知道我在说什么。在任何情况下,curl 在 shell 中运行良好(我怀疑它链接了现代 SSL 支持)所以有时你想在不使用 requestsurllib2 的情况下执行此操作。

        您可以使用subprocess 模块执行curl 并获取检索到的内容:

        import subprocess
        
        // 'response' contains a []byte with the retrieved content.
        // use '-s' to keep curl quiet while it does its job, but
        // it's useful to omit that while you're still writing code
        // so you know if curl is working
        response = subprocess.check_output(['curl', '-s', baseURL % page_num])
        
        

        Python 3 的 subprocess 模块还包含 .run() 以及许多有用的选项。我会把它留给实际运行 python 3 的人来提供答案。

        【讨论】:

          【解决方案5】:

          为了简单起见,也许您应该考虑使用Requests 库。

          带有 json 响应内容的示例如下:

          import requests
          r = requests.get('https://github.com/timeline.json')
          r.json()
          

          如果您想了解更多信息,请在 Quickstart 部分中找到很多工作示例。

          编辑:

          对于您的特定卷曲翻译:

          import requests
          url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
          payload = open("request.json")
          headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
          r = requests.post(url, data=payload, headers=headers)
          

          【讨论】:

          • 请@tricknology,尝试搜索错误,如果您没有找到合适的解决方案,请发布新问题。
          • 如果其他人碰巧看到这个,发生在我身上的原因是我提供了一个字符串作为我的有效负载而不是字典对象。
          • 标题中好像有一个小错字,应该是'Accept-Charset': 'UTF-8'
          • 在发送之前打开文件并解析 JSON 是不必要的低效。您解析 JSON,然后使用 json.dumps() 将其转换回字符串。这是一个糟糕的答案。
          • Requests 是您需要安装和管理的额外依赖项。有关仅使用标准库的简单解决方案,请参阅stackoverflow.com/a/13921930/111995
          【解决方案6】:

          只需使用this website。它将任何 curl 命令转换为 Python、Node.js、PHP、R 或 Go。

          示例:

          curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf
          

          在 Python 中变成这个,

          import requests
          
          headers = {
              'Content-type': 'application/json',
          }
          
          data = '{"text":"Hello, World!"}'
          
          response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)
          

          【讨论】:

          • 为确保您的 JSON 格式正确,请导入“json”模块并在数据负载上使用 json.dumps(payload),即在上述情况下为 data=json.dumps(data)
          【解决方案7】:

          我的答案是 WRT python 2.6.2。

          import commands
          
          status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
          
          print output
          

          我很抱歉没有提供所需的参数,因为它是机密的。

          【讨论】:

          • 如果您需要使用 curl 中的一些特殊选项,例如 --resolve,这就是方法。谢谢。
          • 如何才能在没有表格统计的情况下只获取返回的 json
          【解决方案8】:

          这可以通过下面提到的伪代码方法来实现

          导入操作系统 导入请求 数据 = os.execute(卷曲 URL) R= 数据.json()

          【讨论】:

          • os.system 而不是 os.execute,在这种情况下请求似乎是不必要的
          【解决方案9】:
          curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
          

          它的python实现就像

          import requests
          
          headers = {
              'Content-Type': 'application/json',
          }
          
          params = (
              ('key', 'mykeyhere'),
          )
          
          data = open('request.json')
          response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)
          
          #NB. Original query string below. It seems impossible to parse and
          #reproduce query strings 100% accurately so the one below is given
          #in case the reproduced version is not "correct".
          # response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
          

          检查this link,它将有助于将 cURl 命令转换为 python、php 和 nodejs

          【讨论】:

            【解决方案10】:
            import requests
            url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
            data = requests.get(url).json
            

            也许?

            如果您尝试发送文件

            files = {'request_file': open('request.json', 'rb')}
            r = requests.post(url, files=files)
            print r.text, print r.json
            

            谢谢@LukasGraf 现在我更好地理解了他的原始代码在做什么

            import requests,json
            url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
            my_json_data = json.load(open("request.json"))
            req = requests.post(url,data=my_json_data)
            print req.text
            print 
            print req.json # maybe? 
            

            【讨论】:

            • 这不包括来自requests.json 文件的数据,也没有设置Content-Type: application/json 标头——同样,这将发送GET 请求,而不是POST
            • curl -d @<file> 将读取 字段 以从 <file> 发布 - 这与文件上传不同。
            • @LukasGraf 谢谢 :) ...我不经常使用 curl(阅读:几乎从不)
            • 一个小注,data = requests.get(url).json应该是data = requests.get(url).json()
            • 在 2014 年它是一个属性,现在它是一个函数 :) 很好的调用
            猜你喜欢
            • 2018-10-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-08-11
            • 2014-11-17
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多