control-zed
control-zed

Reputation: 45

closing process.stdout after using subprocess.Popen()

Assume using subprocess.Popen() method to run a basic Shell command - 'ls -l' which gives a list of files in the CWD. Your code will go something like this.

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

Instead of multiple lines, you decide to put it in a single line and end up with

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

I don't see where the p.stdout.close() fits here. Is there any way I could close the stdout of this subprocess? I am using Python 2.6. I know about check_output() in Python 2.7 but I have to stick to 2.6. Is there any potential security or performance issue that I might end up with if I keep opening the output PIPE streams and not closing them?

Upvotes: 0

Views: 2417

Answers (1)

Rohith  Rangaraju
Rohith Rangaraju

Reputation: 84

Probably you can use a with statment for auto close and write the code using oneliner. But before that some ground work can be done. Check out the below code.

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])

Upvotes: 2

Related Questions