且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Python运行Expect脚本的最简单方法

更新时间:2022-01-16 09:20:30

使用 pexpect库.这是Expect功能的Python版本.

Use the pexpect library. This is the Python version for Expect functionality.

示例:

child = pexpect.spawn('Some command that requires password')
child.expect('Enter password:')
child.sendline('password')
child.expect(pexpect.EOF, timeout=None)
cmd_show_data = child.before
cmd_output = cmd_show_data.split('\r\n')
for data in cmd_output:
    print data

Pexpect附带许多示例,可供您学习.要使用interact(),请从示例中查看script.py:

Pexpect comes with lots of examples to learn from. For use of interact(), check out script.py from examples:

(对于Windows,有pexpect的替代方法.)

(For Windows, there is an alternative to pexpect.)