/tmp/somefile" os.popen(cmd) 有时,qry_db会返回错误,但没关系。但我不想将错误打印在 s-6ren">
gpt4 book ai didi

python - 如何在 shell 中运行进程而不在 shell 上打印错误

转载 作者:行者123 更新时间:2023-12-01 05:31:10 24 4
gpt4 key购买 nike

我正在尝试运行这样的流程:

cmd = "qry_db -value x > /tmp/somefile"
os.popen(cmd)

有时,qry_db会返回错误,但没关系。但我不想将错误打印在 shell 上,有什么办法可以做到这一点吗?

最佳答案

不要使用os.popen()。请改用 subprocess 模块:

import subprocess

with open('/tmp/somefile', 'w') as tmpfile:
subprocess.call(['qry_db', '-value', 'x'], stdout=tmpfile, stderr=subprocess.DEVNULL)

这会将 stderr 重定向到 /dev/null,有效地消除错误。 stdout 仍会重定向到您的临时文件。您可能想使用subprocess.check_output()来代替它。 ,将输出直接读入 Python 脚本。您仍然可以使用 stderr=subprocess.DEVNULL 来消除错误输出。

subprocess.DEVNULL 是在 Python 3.3 中添加的。如果您使用的是早期版本的 Python,请使用:

import subprocess
import os

with open('/tmp/somefile', 'w') as tmpfile, open(os.devnull) as devnull:
subprocess.call(['qry_db', '-value', 'x'], stdout=tmpfile, stderr=devnull)

关于python - 如何在 shell 中运行进程而不在 shell 上打印错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com