要传递的Python子进程是/N

2024-04-19 08:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有命令要求输入“是”。如何自动传递这个答案?在

我使用了下面的代码,但它不起作用。在

from subprocess import Popen, PIPE
foo_proc = Popen([cmd], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['YES'], stdout=foo_proc.stdin)
foo_output = foo_proc.communicate()[0]
yes_proc.wait()

我得到的错误:

^{pr2}$

我用的是Python2.7


Tags: 答案代码fromimport命令cmdfoostdin
2条回答

我建议直接在Popen语句中使用简单的管道命令。您可以使用以下选项-

foo_proc = Popen(['echo' , 'yes', '|', cmd])

您需要使用shell=True,例如

^{pr2}$

有关详细信息,请参阅(this link)

对于CLI交互,我将使用Python模块来控制伪终端中的交互式程序,比如Pexpect。在

它将允许您执行类似和更复杂的任务:

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
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('lcd /tmp')
child.expect('ftp> ')
child.sendline('cd pub/OpenBSD')
child.expect('ftp> ')
child.sendline('get README')
child.expect('ftp> ')
child.sendline('bye')

您可以找到它的文档here。在

相关问题 更多 >