3

I have a python program which uses various Bash shell scripts. However, some of them require (y/n) input. I know the input required based on the question number so it's a matter of being able to provide that automatically.

Is there a way in Python to do that?

As a last resort I can send a signal to a window etc. but I'd rather not do that.

4

2 回答 2

3

可能最简单的方法是使用pexpect。一个示例(来自wiki 中的概述):

import pexpect

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('noah@example.com')
child.expect('ftp> ')
child.sendline('cd pub')
child.expect('ftp> ')
child.sendline('get ls-lR.gz')
child.expect('ftp> ')
child.sendline('bye')

如果您不想使用额外的模块,使用subprocess.Popen是可行的方法,但它更复杂。首先,您创建流程。

import subprocess

script = subprocess.Popen(['script.sh'], stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, shell=True)

您可以在shell=True此处使用,也可以将 shell 的名称添加到命令参数中。前者更容易。

接下来,您需要阅读,script.stdout直到找到您的问题编号。然后你写答案script.stdin

于 2012-11-06T21:52:48.267 回答
3

使用subprocess.Popen.

from subprocess import Popen, PIPE


popen = Popen(command, stdin=PIPE)
popen.communicate('y')
于 2012-11-06T20:03:28.473 回答