python curl 执行带参数的命令

标签 python subprocess

我需要执行以下命令

curl -v -H 'X-Auth-User: myaccount:me' -H 'X-Auth-Key: secretpassword' http://localhost:8080/auth/v1.0/

当我从终端运行它时,它运行良好。并给我如下结果

* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /auth/v1.0/ HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:8080
> Accept: */*
> X-Auth-User: myaccount:me
> X-Auth-Key: secretpassword
> 
< HTTP/1.1 200 OK
< X-Storage-Url: http://localhost:8080/v1/AUTH_myaccount
< X-Auth-Token: AUTH_tk8bf07349d36041339450f0b46a2adc39
< Content-Type: text/html; charset=UTF-8
< X-Storage-Token: AUTH_tk8bf07349d36041339450f0b46a2adc39
< Content-Length: 0
< X-Trans-Id: tx99a9e2a129f34ab487ace-00553cb059
< Date: Sun, 26 Apr 2015 09:31:05 GMT
< 
* Connection #0 to host localhost left intact

但我需要从 python 运行它。我通过以下方式使用了 subprocess.call 和 subprocess.popen

import subprocess
subprocess.call(["curl", "-v -H 'X-Auth-User: myaccount:me' -H 'X-Auth-Key: secretpassword' http://localhost:8080/auth/v1.0/"], shell=False)

但是我遇到了以下错误

curl: option -v -H 'X-Auth-User: myaccount:me' -H 'X-Auth-Key: secretpassword' http://localhost:8080/auth/v1.0/: is unknown
curl: try 'curl --help' or 'curl --manual' for more information

使用打开

result = subprocess.Popen(["curl", "-v -H 'X-Auth-User: myaccount:me' -H 'X-Auth-Key: secretpassword' http://localhost:8080/auth/v1.0/"])
print(result)

并为此得到错误

curl: option -v -H 'X-Auth-User: myaccount:me' -H 'X-Auth-Key: secretpassword' http://localhost:8080/auth/v1.0/: is unknown
curl: try 'curl --help' or 'curl --manual' for more information
<subprocess.Popen object at 0x7fd003d82cd0>

如何解决这个问题???

最佳答案

由于call需要传递一个命令行参数数组,你可以自己拆分命令行,这样调用:

subprocess.call([
    "curl", "-v", "-H", "X-Auth-User: myaccount:me", "-H", 
    "X-Auth-Key: secretpassword", "http://localhost:8080/auth/v1.0/"
], shell=False)

关于python curl 执行带参数的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875920/

相关文章:

python-3.x - Subprocess.Popen 与 .call : What is the correct way to call a C-executable from shell script using python where all 6 jobs can run in parallel

python - 在 for 循环中使用 unpack 与在 python 中不使用 unpack 有什么区别

python - 如何将巨大的 Pandas 数据框保存到 hdfs?

python - 来自大型掩码数组的 Numpy 平均值

python - 8 拼图计算邻居 python

python - Tkinter 复选按钮不起作用

python - Python 中带有子进程的 Shell 管道

python - 如何 "adopt"python中的子进程

python - 子进程长度限制

python - 如何在不使用子进程的情况下从 python 自动化脚本中运行 python 'sdist' 命令?