Search code examples
pythondjangolinuxunixpopen

convert os.popen command to a subprocess.Popen instance


According to python docs http://docs.python.org/library/subprocess.html, it's recommended to replace os.popen with the Popen class, right now I have the following command:

import os
c = "openssl dgst -sha1 -sign /foo/1 /bar/1 | openssl enc -base64 -A"
my_value = os.popen(c).read()

I understand that Popen takes the command as a list of string arguments, how ever it breaks when I try to pass pipe ("|"), I also understand this is caused because "|" has a special meaning in bash, how ever not sure how to solve this issue.

The other issue is Popen instances don't have read method so I'm not sure what is the way to see the output.

I am using Django Framework, so If there is also a function in the framework that may help is also an option.


Solution

  • If you take a look at the Replacing the shell pipeline section in the documentation, you'll see that your example could be written as follows using subprocess:

    from subprocess import Popen, PIPE                                        
    p_dgst = Popen("openssl dgst -sha1 -sign /foo/1 /bar/1".split(),
                   stdout=PIPE)
    p_enc =  Popen("openssl enc -base64 -A".split(),
                   stdin=p_dgst.stdout, stdout.PIPE)
    my_value = p_enc.communicate()[0]