os.devnull 和 subprocess.pipe 的区别

我一直想知道如何打印从Python的外壳输出subprocess.call()的分配open(os.devnull, 'w')subprocess.PIPEstdout值:

subprocess.call(command, stdout=open(os.devnull, 'w'), shell=True)

subprocess.call(command, stdout=subprocess.PIPE, shell=True)

这两行都谨慎地执行存储在命令变量中的 shell 命令(终端上没有输出) - 但我不知道两者之间的区别。我是使用子流程的新手。


守候你守候我
浏览 1285回答 2
2回答

红糖糍粑

第一种方法是将标准输出重定向到一个文件(POSIX 中的 /dev/null),而第二种方法是构建一个 PIPE 将输出重定向到特定的流。来自命令 help() 的 subprocess.PIPE 的官方定义:“该模块允许您生成进程,连接到它们的输入/输出/错误管道,并获取它们的返回代码。”我会说这种方法就像:我们只是将一些东西放在消息队列(内存)中一段时间以备后用。但是 subprocess.call 只是返回状态码。似乎您无法引用返回值,subprocess.call(command, stdout=open(os.devnull, 'w'), shell=True)因此无法通过`subprocess.call(command, stdin=the_stdout, shell=True) 引用该值。很难在两个命令之间建立连接。基于本文中的信息:http : //blog.acipo.com/running-shell-commands-in-python/还有 Python 2.7 文档:https : //docs.python.org/2/library/subprocess.html建议我们可以将 Popen 与 communication() 一起使用Popen 是 Python 3 提供的高级类。 关于这个有一个很好的资源:https : //stackabuse.com/pythons-os-and-subprocess-popen-commands/

DIEA

devnull 在 linux 中指向 /dev/null。当您写入 /dev/null 时,它将丢弃收到的所有内容。管道有两端,当你写到一端时,另一端会收到你写的消息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python