开发者

How do I redirect stdin/stdout when I have a sequence of commands in Bash?

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开发者_如何学Python 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.


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

(cmd0 </dev/null; cmd1) | cmd2


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜