I know how to run a command using cmd = subprocess.Popen and then subprocess.communicate. Most of the time I use a string tokenized with shlex.split as 'argv' argument for Popen. Example with "ls -l":
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
However, pipes seem not to work... For instance, the following example returns noting:
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l | sed "s/a/b/g"'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
Can you tell me what I am doing wrong please?
Thx
I've made a little function to help with the piping, hope it helps. It will chain Popens as needed.
""" Why don't you use shell
"""
def output_shell(line):
shlex
only splits up spaces according to the shell rules, but does not deal with pipes.It should, however, work this way:
according to
help(subprocess)
'sHTH
I think you want to instantiate two separate Popen objects here, one for 'ls' and the other for 'sed'. You'll want to pass the first Popen object's
stdout
attribute as thestdin
argument to the 2nd Popen object.Example:
You can keep chaining this way if you have more commands:
See the subprocess documentation for more info on how to work with subprocesses.