【问题标题】:How to execute a curl command in Python and get the response and pass it through other code如何在 Python 中执行 curl 命令并获取响应并将其传递给其他代码
【发布时间】:2020-05-27 16:49:20
【问题描述】:

我有一个 curl 命令。我想在 Python 中执行并获取响应以将其传递给其他代码。

curl https://api.box.com/oauth2/token -d 'grant_type=refresh_token' -d 'refresh_token=Ew38UXVKS3kc0axFt6MdDklUnoHpipxTzDWBmKlXAG9ImvGafbbaUhQndv89e677' -d 'client_id=3qkm5h4wh765b3khiws0z8hdpkc56jhs' -d 'client_secret=h9AeXzZL3KATJuaHmimFFBRBDZQrp9tr' -X POST

如何在 Python 中执行脚本并获取响应并通过其他代码传递?

当我在 CMD 中执行 curl 脚本时,我收到以下响应:

{"access_token":"uz843jpIiEWnu0CcuT9as2XbA3UEQTR67","expires_in":4261,"restricted_to":[],"refresh_token":"GsDaP6VyUpHN8vDHbz9ktAjLfMLN0dFL6PMIK4fmDH8eKRqR360vDhQTBhIMZxy67","token_type":"bearer"}

从上面的回复中,我需要获取access_token 的值。

【问题讨论】:

    标签: python-3.x curl libcurl pycurl shlex


    【解决方案1】:

    就像 avloss 所说 - 试试 requests

    另一个很棒的资源是应用程序Postman

    它可以让您尝试任何您想要的 http 调用,然后还可以为您(以及许多其他语言)将其转换为 curl 和/或 python 请求代码。

    当我试图弄清楚如何将requests 用于除了简单的 http 调用之外的任何事情时,我发现它非常有用。

    【讨论】:

    • 嗨,理查德,我在执行上述命令后没有得到响应。
    • 哪个代码? avloss'蟒蛇?我的建议是首先尝试让您查询在 Postman 中工作。然后在它在那里工作之后使用 Postman 生成等效的 python 请求调用。
    【解决方案2】:

    你应该使用requests库(pip install requests

    import requests
    url = 'https://api.box.com/oauth2/token'
    data = {
        'grant_type':'refresh_token',
        'refresh_token':'***',
        'client_id':'***',
        'client_secret':'***'
    }
    response = requests.post(url, data).json()
    print(response)
    

    【讨论】:

    • 感谢您的更新。但我在尝试执行脚本时看到以下错误。
    • “Response 200”通常意味着成功,我不确定你是怎么得到这个错误的。
    • 我认为这是一个错误,因为我无法看到响应。请告诉我如何才能看到如下响应。{"access_token":"uz843jpIiEWnu0CcuT9as2XbA3UEQTR67","expires_in ":4261,"restricted_to":[],"refresh_token":"GsDaP6VyUpHN8vDHbz9ktAjLfMLN0dFL6PMIK4fmDH8eKRqR360vDhQTBhIMZxy67","token_type":"bearer"}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2016-06-29
    • 1970-01-01
    相关资源
    最近更新 更多