2

如何在 Python 中运行以下命令?

/some/path/and/exec arg > /dev/null

我懂了:

call(["/some/path/and/exec","arg"])

如何像往常一样插入exec进程的输出/dev/null并保持我的 python 进程的打印输出?如,不要将所有内容重定向到标准输出?

4

1 回答 1

7

对于 Python 3.3 及更高版本,只需使用subprocess.DEVNULL

call(["/some/path/and/exec","arg"], stdout=DEVNULL, stderr=DEVNULL)

请注意,这会同时重定向stdoutstderr。如果您只想重定向stdout(正如您的sh行所暗示的那样),请忽略该stderr=DEVNULL部分。

如果需要兼容旧版本,可以使用os.devnull. 因此,这适用于从 2.6 开始的所有内容(包括 3.3):

with open(os.devnull, 'w') as devnull:
    call(["/some/path/and/exec","arg"], stdout=devnull, stderr=devnull)

或者,对于 2.4 及更高版本(仍包括 3.3):

devnull = open(os.devnull, 'w')
try:
    call(["/some/path/and/exec","arg"], stdout=devnull, stderr=devnull)
finally:
    devnull.close()

在 2.4 之前,没有subprocess模块,所以你可以合理地回溯到尽可能远的地方。

于 2013-01-06T13:09:33.697 回答