我在 Windows 命令行提示符下运行curl 命令。它产生一个 json
输出。该命令如下所示:
curl --data "action=details&user=user&project=project1&problemid=2021" https://website:9020/
我在 python 中发出相同的命令,如下所示:
import subprocess
output = subprocess.run(
[
"curl",
"--data",
"\"action=details&user=user&project=project1&problemid=2021\""
"https://website:9020/",
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True,
)
print(output.stdout.decode("utf-8"))
输出如下:
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 199 100 64 100 123 64 123 0:00:01 --:--:-- 0:00:01 1254
{"status":400,"message":"Action parameter is missing"}
但是命令行会生成 json 输出。然而,通过 subprocess.run 发出的相同命令会产生此错误。我还尝试了 subprocess.Popen
和 subprocess.check_output
。同样的问题仍然存在。我在这里做错了什么导致了这个错误?
最佳答案
在某些情况下(例如,如果需要以管理员身份运行命令行),subprocess
可能不是执行命令行命令的正确选择。
您可以使用 os.system() 来查看输出,或使用 os.popen() 来读取和存储输出。
import os
import json
# to see the output
print(os.system("curl --data \"action=details&user=user&project=project1&problemid=2021\" https://website:9020/")
output = os.popen("curl --data \"action=details&user=user&project=project1&problemid=2021\" https://website:9020/").read()
outputjson = json.loads(output)
然后就可以访问json
信息了。
关于python - Curl 在子进程中生成状态 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68292065/