使用Popen.stdin执行多个命令 [英] Executing multiple commands using Popen.stdin

查看:595
本文介绍了使用Popen.stdin执行多个命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用管道在从python脚本启动的独立应用程序中执行多个命令.我可以可靠地将命令传递到程序的stdin的唯一方法是使用Popen.communicate,但是在命令执行后它会关闭程序.如果我使用Popen.stdin.write,则该命令仅在5次左右中执行1次,因此无法可靠运行.我在做什么错了?

I'd like to execute multiple commands in a standalone application launched from a python script, using pipes. The only way I could reliably pass the commands to the stdin of the program was using Popen.communicate but it closes the program after the command gets executed. If I use Popen.stdin.write than the command executes only 1 time out of 5 or so, it does not work reliable. What am I doing wrong?

详细说明:

我有一个应用程序,它侦听stdin的命令并逐行执行它们. 我希望能够基于用户与GUI的交互来运行该应用程序并将各种命令传递给它. 这是一个简单的测试示例:

I have an application that listens to stdin for commands and executes them line by line. I'd like to be able to run the application and pass various commands to it, based on the users interaction with a GUI. This is a simple test example:

import os, string
from subprocess import Popen, PIPE

command = "anApplication" 
process = Popen(command, shell=False, stderr=None, stdin=PIPE)

process.stdin.write("doSomething1\n")
process.stdin.flush()
process.stdin.write("doSomething2\n")
process.stdin.flush()

我希望看到两个命令的结果,但是没有任何反应. (如果我多次执行Popen.write行之一,则偶尔会起作用.)

I'd expect to see the result of both commands but I don't get any response. (If I execute one of the Popen.write lines multiple times it occasionally works.)

如果我执行:

process.communicate("doSomething1")

它工作正常,但应用程序终止.

it works perfectly but the application terminates.

推荐答案

如果我正确理解了您的问题,则希望与控制台应用程序进行交互(即发送命令并读取响应).

If I understand your problem correctly, you want to interact (i.e. send commands and read the responses) with a console application.

如果是这样,您可能要检查类似Expect的库,例如Python的pexpect: http://pexpect.sourceforge .net

If so, you may want to check an Expect-like library, like pexpect for Python: http://pexpect.sourceforge.net

这将使您的生活更加轻松,因为它将处理同步,这也是ddaa所描述的问题.也可以看看: http://www.noah.org/wiki/Pexpect#问:_Why_not_just_use_a_pipe_.28popen.28.29.29.3F

It will make your life easier, because it will take care of synchronization, the problem that ddaa also describes. See also: http://www.noah.org/wiki/Pexpect#Q:_Why_not_just_use_a_pipe_.28popen.28.29.29.3F

这篇关于使用Popen.stdin执行多个命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆