Friday, 23 August 2013

Subprocess module from python fails to run bash commands like " | "

Subprocess module from python fails to run bash commands like " | "

The following python script:
#!/usr/bin/env python
import os
cmd = "echo Hello world | cut -d' ' -f1"
test=os.system(cmd)
print(test)
it runs ok (the output is Hello). But when I use subprocess module this one:
#!/usr/bin/env python
import subprocess
cmd = "echo Hello world | cut -d' ' -f1"
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
test = process.communicate()[0]
print (test)
is not ok. The output is Hello world | cut -d' ' -f1 and I expect to be
only Hello. How can I correct it?
I saw that in general subprocess module will fail when I'm using a bash
command like:
<cmd1> | <cmd2>

No comments:

Post a Comment