Python: os.system() 无返回或错误

0 投票
2 回答
12063 浏览
提问于 2025-04-17 08:47

我在我的脚本里需要用到os.system()几次,但我不想让命令行的错误信息出现在脚本的窗口里。有没有什么办法可以做到这一点?我想这有点像是静默执行命令,执行完毕后不返回任何文本。我不能用'try',因为那不是Python的错误。

2 个回答

2

调用一个子进程并处理它的标准输出和标准错误的推荐方法是使用subprocess模块。下面是如何同时屏蔽标准输出和标准错误的方法:

import subprocess

# New process, connected to the Python interpreter through pipes:
prog = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prog.communicate()  # Returns (stdoutdata, stderrdata): stdout and stderr are ignored, here
if prog.returncode:
    raise Exception('program returned error code {0}'.format(prog.returncode))

如果你希望子进程能够打印到标准输出,你只需要去掉stdout=…这一部分就可以了。

4

你可以把命令的错误信息从终端中转移出去。比如说:

# without redirect
In [2]: os.system('ls xyz')
ls: cannot access xyz: No such file or directory
Out[2]: 512

# with redirect
In [3]: os.system('ls xyz 2> /dev/null')
Out[3]: 512

另外,正如@Spencer Rathbun提到的,应该优先使用subprocess模块,而不是os.system()。因为它可以让你更直接地控制子进程的输出和错误信息。

撰写回答