繁体   English   中英

使用subprocess.Popen()后关闭process.stdout

[英]closing process.stdout after using subprocess.Popen()

假设使用subprocess.Popen()方法运行基本的Shell命令'ls -l' ,该命令给出了CWD中的文件列表。 您的代码将像这样。

from subprocess import Popen,PIPE
p=Popen(['ls','-l'],stdout=PIPE)
print p.communicate()[0]
p.stdout.close()

您决定将其放在一行中,而不是多行,最后得到

print Popen(['ls','-l'],stdout=PIPE).communicate()[0]

我看不到p.stdout.close()适合的位置。 有什么办法可以关闭此子进程的stdout? 我正在使用Python 2.6 我知道Python 2.7中的check_output() ,但我必须坚持使用2.6。 如果我继续打开输出PIPE流而不关闭它们,是否可能会遇到潜在的安全性或性能问题?

可能您可以使用with语句自动关闭并使用oneliner编写代码。 但在此之前,可以做一些基础工作。 查看以下代码

from subprocess import Popen

class MyPopen(Popen):

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        if self.stdout:
            self.stdout.close()
        if self.stderr:
            self.stderr.close()
        if self.stdin:
            self.stdin.close()
        # Wait for the process to terminate, to avoid zombies.
        self.wait()

if __name__ == '__main__':
    with MyPopen(['ls','-l'],stdout=PIPE) as p:
        print(p.communicate()[0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM