如何在Python中运行以下代码?
How do I run the following in Python?
/some/path/and/exec arg > /dev/null我知道了:
call(["/some/path/and/exec","arg"])如何将 exec 进程的输出插入到/dev/null 并保持python进程的打印输出正常?在这种情况下,不要将所有内容都重定向到stdout吗?
How do I insert the output of the exec process to /dev/null and keep the print output of my python process as usual? As in, don't redirect everything to stdout?
推荐答案对于Python 3.3和更高版本,只需使用 subprocess.DEVNULL :
For Python 3.3 and later, just use subprocess.DEVNULL:
call(["/some/path/and/exec","arg"], stdout=DEVNULL, stderr=DEVNULL)请注意,这将同时重定向 stdout 和 stderr .如果您只想重定向 stdout (如您的 sh 行所暗示的那样),则省去 stderr = DEVNULL 部分.
Note that this redirects both stdout and stderr. If you only wanted to redirect stdout (as your sh line implies you might), leave out the stderr=DEVNULL part.
如果您需要与旧版本兼容,则可以使用 os.devnull .因此,这适用于2.6(含3.3)以上的所有版本:
If you need to be compatible with older versions, you can use os.devnull. So, this works for everything from 2.6 on (including 3.3):
with open(os.devnull, 'w') as devnull: call(["/some/path/and/exec","arg"], stdout=devnull, stderr=devnull)或者,对于2.4及更高版本(仍包括3.3):
Or, for 2.4 and later (still including 3.3):
devnull = open(os.devnull, 'w') try: call(["/some/path/and/exec","arg"], stdout=devnull, stderr=devnull) finally: devnull.close()在2.4之前,没有 subprocess 模块,因此可以回想起.
Before 2.4, there was no subprocess module, so that's as far back as you can reasonably go.
更多推荐
在python中将进程运行到/dev/null
发布评论