当我在 Bash 中有一系列命令时,如何重定向 stdin/stdout?
我当前正在执行一个 Bash 命令(通过 Python 的 subprocess.Popen
),该命令从 stdin
读取数据,执行某些操作并输出到 stdout
。 是
pid = subprocess.Popen( ["-c", "cmd1 | cmd2"],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
shell =True )
output_data = pid.communicate( "input data\n" )
现在,我想做的是更改它以在同一个子 shell 中执行另一个命令,该命令将在下一个命令执行之前改变状态,所以我的 shell 命令行现在(概念上)将
cmd0; cmd1 | cmd2
:在这种情况下,有什么方法可以将输入发送到 cmd1
而不是 cmd0
吗?我假设输出将包括 cmd0
的输出(将为空),然后是 cmd2
的输出。
cmd0
实际上不应该从 stdin
读取任何内容,这在这种情况下有什么不同吗?
我知道这可能只是一种愚蠢的方法,我试图在 cmd0 中进行修补,而不会对其他代码进行太大的更改。也就是说,如果有更简洁的方法来解决这个问题,我愿意接受建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在子 shell 中执行 cmd0 和 cmd1 并将 /dev/null 重定向为 cmd0 的 stdin:
execute cmd0 and cmd1 in a subshell and redirect /dev/null as stdin for cmd0:
我认为你不必做任何特别的事情。如果 cmd0 不接触标准输入,那么它对 cmd1 来说是完整的。自己尝试一下:(
使用 ls 作为任意命令来为管道生成几行输入)
当然,到 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:
(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.
好的,我想我可以将
stdin
文件描述符复制到临时文件描述符,关闭它,运行cmd0
,然后在运行cmd1
之前恢复它code>:不确定是否可以通过这种方式重定向 stdin,目前无法对此进行测试。
http://tldp.org/LDP/abs/html/io-redirection。 html
http://tldp.org/LDP/abs/html/x17601 .html
Ok, I think I may be able to duplicate the
stdin
file descriptor to a temporary one, close it, runcmd0
, then restore it before runningcmd1
: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