在python中的popen中输入/返回键的编码

时间:2013-02-20 09:43:28

标签: python subprocess popen

代码将用Python编写,以自动运行带参数的进程并解析其输出。

命令process_name将在命令行上使用参数arg1arg2运行,并在执行期间输入input1input2作为输入。所以在python中,它与Popen一起运行,如代码所示:

process_object = subprocess.Popen(['process_name','arg1','arg2','input1','input2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

此处,process_name可以是特定操作系统(Linux,Mac,Windows)中的任何可执行命令。

在执行特定命令期间,会出现一个输入提示:

Do you want to continue(y/N):

Do you want to continue(Y/n):

首先提示意味着如果输入为空且按下返回键,则默认输入为N。同样,第二个提示的默认输入是Y

还有另一个提示:

Hit Enter to do this action

除了返回键之外,其他任何内容都不能被进程命令接受。

在没有命令行参数的情况下手动运行命令并在执行期间使用输入

abc
def
             ##this is blank because return key is not printable

然后成功执行。

在Python中自动化为:

process_object = subprocess.Popen(['process_name','abc','def',''], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

然后它不会被执行。

同样的情况:

process_object = subprocess.Popen(['process_name','abc','def','\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

在StackOverflow上的answer中,有一个逻辑用于对键盘上的箭头键进行编码,并且在此link中有一个ANSI转义序列表。因此,返回键的ANSI代码是'\ x1B13'并使用它,代码被修改为

process_object = subprocess.Popen(['process_name','abc','def','\x1B13'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

但是,它没有用。

代码已更改为:

process_object = subprocess.Popen(['process_name','abc','def'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process_object.communicate('')

还有另一个参数stdin在执行期间为进程提供输入。输入提供给方法communication(),它接受输入''作为返回键输入。所以这段代码成功地执行了这个过程。

但是,这种方法对于输入流如下所示的命令不起作用:

abc
def

ghi
jkl

所以,代码改为:

process_object = subprocess.Popen(['process_name','abc','def'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process_object.communicate(' ghi jkl')

它不起作用。

如果代码更改为

process_object = subprocess.Popen(['process_name','abc','def'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process_object.communicate('')
process_object.communicate('ghi')
process_object.communicate('jkl')

然后发生错误:

ValueError: I/O operation on closed file

那么,如何让它工作,以便在代码本身的Python代码中接受夹在两个非空字符串之间的返回键输入?

1 个答案:

答案 0 :(得分:1)

我建议你试试pexpect,它更适合这项任务(实际上, 是为这类任务而构建的工具)。

您还可以浏览examples并查看其用途。

相关问题