Python持久Popen
有没有办法在 Popen 的同一个“会话”中进行多次调用? 例如,我可以通过它进行一次调用,然后再进行一次调用,而不必将命令连接成一个长字符串吗?
Is there a way to do multiple calls in the same "session" in Popen? For instance, can I make a call through it and then another one after it without having to concatenate the commands into one long string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您使用 popen 时,您并不是在“拨打电话”,而是在运行一个可执行文件并通过 stdin、stdout 和 stderr 与它对话。 如果可执行文件有某种方式来执行“会话”工作(例如,通过从标准输入读取行),那么,是的,您可以做到这一点。 否则,您将需要执行多次。
subprocess.Popen(大部分)只是 execvp(3) 的包装器
You're not "making a call" when you use popen, you're running an executable and talking to it over stdin, stdout, and stderr. If the executable has some way of doing a "session" of work (for instance, by reading lines from stdin) then, yes, you can do it. Otherwise, you'll need to exec multiple times.
subprocess.Popen is (mostly) just a wrapper around execvp(3)
假设您希望能够运行 shell 并向其发送多个命令(并读取它们的输出),那么您似乎可以执行以下操作:
之后,例如:(
当然,您应该检查 stderr code> 也一样,或者要求
Popen
将其与stdout
合并)。 上述的一个主要问题是stdin
和stdout
管道处于阻塞模式,因此很容易“卡住”永远等待从外壳输出。 虽然我还没有尝试过,但 ActiveState 网站上有一个食谱,展示了如何解决这个问题。更新:查看相关问题/答案后,看起来使用Python内置的
select
模块来查看是否有数据可以读取< code>stdout (当然,您也应该对stderr
执行相同的操作),例如:Assuming you want to be able to run a shell and send it multiple commands (and read their output), it appears you can do something like this:
After which, e.g.,:
(Of course, you should check
stderr
too, or else askPopen
to merge it withstdout
). One major problem with the above is that thestdin
andstdout
pipes are in blocking mode, so it's easy to get "stuck" waiting forever for output from the shell. Although I haven't tried it, there's a recipe at the ActiveState site that shows how to address this.Update: after looking at the related questions/answers, it looks like it might be simpler to just use Python's built-in
select
module to see if there's data to read onstdout
(you should also do the same forstderr
, of course), e.g.:听起来你正在使用 shell=True 。 除非你需要,否则不要这样做。 相反,使用 shell=False (默认值)并传入命令/参数列表。
您有什么理由不能只创建两个 Popen 实例并根据需要在每个实例上等待/通信? 如果我理解正确的话,这是正常的做法。
Sounds like you're using shell=True. Don't, unless you need to. Instead use shell=False (the default) and pass in a command/arg list.
Any reason you can't just create two Popen instances and wait/communicate on each as necessary? That's the normal way to do it, if I understand you correctly.