Python 捕获子进程中的成功或失败

标签 python curl

这是Python代码片段。我正在尝试获取curl命令的结果。 (注意:我可以使用请求模块而不是调用curl命令,但由于某些复杂性原因,哪个请求模块不起作用,我最终使用了该命令)

我使用子进程捕获curl 输出并将成功/错误输出存储在stdout 和stderr 中。在本例中,我看到脚本同时打印成功和失败。然而,最后,我想根据结果获得成功/错误,而不是两者。有人可以解释一下这里可能出了什么问题

counter = 1
for url in urls:
    command = 'curl ' + acceptance_url
    args = command.split()
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()


    if stdout is not None:
        print "Success: %s" % (stdout)


    if stderr is not None:
        print "Error: %s" %(stderr)

最佳答案

您不应该检查它是否不是 None,而是将其转换为正表达式:

if stdout:
   print "Success: %s" % (stdout)

if stderr:
   print "Error: %s" %(stderr)

您还可以检查

Popen.returncode: The child return code, set by poll() and wait() (and indirectly by communicate()).

查看命令是否成功。

关于Python 捕获子进程中的成功或失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43884457/

相关文章:

linux -/~/software/ParticleRuntime/v84/bin/glnxa64/libcurl.so.4 : no version information available (required by curl)

python - Django 的逻辑或多对多查询返回重复结果

python - 为什么我的二分算法不起作用? Python

python - 查找 xy 数据点图与 numpy 的所有交集?

php - 如何从 php curl 访问洋葱网站?

node.js - 带有 Postman 请求的 Twilio Webhook

python - 重新排序三个列表并保持索引之间的关系?

python - Plotly:使用 plotly express line 时如何在 hoverinfo 中格式化日期?

c - 如何从源代码而不是开发包安装 header

c++ - 将 cURL 内容结果保存到 C++ 中的字符串中