views:

219

answers:

3

I've currently got a Bash command being executed (via Python's subprocess.Popen) which is reading from stdin, doing something and outputing to stdout. Something along the lines of:

pid = subprocess.Popen( ["-c", "cmd1 | cmd2"],
                       stdin = subprocess.PIPE, 
                       stdout = subprocess.PIPE, 
                       shell =True )
output_data = pid.communicate( "input data\n" )

Now, what I want to do is to change that to execute another command in that same subshell that will alter the state before the next commands execute, so my shell command line will now (conceptually) be:

cmd0; cmd1 | cmd2

Is there any way to have the input sent to cmd1 instead of cmd0 in this scenario? I'm assuming the output will include cmd0's output (which will be empty) followed by cmd2's output.

cmd0 shouldn't actually read anything from stdin, does that make a difference in this situation?

I know this is probably just a dumb way of doing this, I'm trying to patch in cmd0 without altering the other code too significantly. That said, I'm open to suggestions if there's a much cleaner way to approach this.

+1  A: 

I don't think you should have to do anything special. If cmd0 doesn't touch stdin, it'll be intact for cmd1. Try for yourself:

ls | ( echo "foo"; sed 's/^/input: /')

(Using ls as an arbitrary command to produce a few lines of input for the pipeline)

And the additional pipe to cmd2 doesn't affect the input either, of course.

Jefromi
Ok, that looks good and is what I needed to know. Will try it out when I can.
Tom
+4  A: 

execute cmd0 and cmd1 in a subshell and redirect /dev/null as stdin for cmd0:

(cmd0 </dev/null; cmd1) | cmd2
Jürgen Hötzel
+1: though the OP said cmd0 won't touch stdin, good to be safe!
Jefromi
A: 

Ok, I think I may be able to duplicate the stdin file descriptor to a temporary one, close it, run cmd0, then restore it before running cmd1:

exec 0>&3; exec 0<&-; cmd0 ; exec 3>&0 ; cmd1 | cmd2

Not sure if it's possible to redirect stdin in this way though, and can't test this at the moment.

http://tldp.org/LDP/abs/html/io-redirection.html

http://tldp.org/LDP/abs/html/x17601.html

Tom
ok, this is probably not necessary (even if it was going to work) given the other answers people have given.
Tom