在python中将进程运行到/dev/null

编程入门 行业动态 更新时间:2024-10-22 23:02:56
本文介绍了在python中将进程运行到/dev/null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在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

本文发布于:2023-10-25 08:19:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   进程   python   dev   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!