如何运行带有管道的命令|?
子进程模块看起来很复杂......
有没有类似的东西
output,error = `ps cax | grep something`
Run Code Online (Sandbox Code Playgroud)
在shell脚本中?
第17.1.4.2节:替换 python子进程模块的shell管道表示要替换
output=`dmesg | grep hda`
Run Code Online (Sandbox Code Playgroud)
同
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
Run Code Online (Sandbox Code Playgroud)
对第三行的评论解释了为什么调用close函数,而不是为什么它有意义.对我来说,它没有.调用通信方法之前是否会关闭p1.stdout以防止通过管道发送任何输出?(显然它不会,我试图运行代码,它运行正常).为什么有必要调用close来使p1接收SIGPIPE?什么样的亲密关闭?究竟是什么关闭?
请考虑这是一个学术问题,除了更好地理解这些事情之外我不想做任何事情.
我正在阅读子流程模块部分中有关 Popen 类的 Python 文档,我遇到了以下代码:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
Run Code Online (Sandbox Code Playgroud)
该文件还指出
“启动 p2 后的 p1.stdout.close() 调用很重要,如果 p2 在 p1 之前退出,p1 会收到 SIGPIPE。
为什么必须在我们接收 SIGPIPE 之前关闭 p1.stdout,如果我们已经关闭了 p1,那么 p1 如何知道 p2 在 p1 之前退出?