我为 C 程序开发了一个 Python 图形用户界面。该程序要求输入两个密码。 如何等待密码提示,然后在代码中插入密码?
目前我尝试通过以下方式做到这一点:
subprocess.popen.communicate(input)
但这不起作用,因为程序会再次在 shell 中要求输入密码。
程序流程如下:
- shell:使用一些参数执行程序
- 标准输出:“请插入密码 1”
- 标准输入:pw1
- 标准输出:“请插入密码 2”
- 标准输入:pw2
请您参考如下方法:
你应该考虑使用另一个库:Pexpect
Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes’ Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.
这是连接到 FTP 服务器时提供用户名和密码的代码示例:
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('bob')
child.expect('Password:')
child.sendline('thisisnotasecurepassword')
