使用python从另一个脚本处理交互式脚本

时间:2011-05-17 12:50:11

标签: python

我有一个shell脚本,这个是交互式的,我正在创建一些自动化来为这个shell脚本提供输入。使用Python完成自动化。例如,

shell脚本等待输入,例如“域名是什么?” 现在python应该能够提供输入并按ENTER键。

请提供一些处理此类会话的解决方案。

1 个答案:

答案 0 :(得分:4)

pexpect:http://pypi.python.org/pypi/pexpect/

它带有一堆例子。例如这个用于ftp:

import pexpect
import sys

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')
child.sendline('bin')
child.expect('ftp> ')
child.sendline('prompt')
child.expect('ftp> ')
child.sendline('pwd')
child.expect('ftp> ')
print("Escape character is '^]'.\n")
sys.stdout.write (child.after)
sys.stdout.flush()
child.interact() # Escape character defaults to ^]
# At this point this script blocks until the user presses the escape character
# or until the child exits. The human user and the child should be talking
# to each other now.

# At this point the script is running again.
print 'Left interactve mode.'

# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
if child.isalive():
    child.sendline('bye') # Try to ask ftp child to exit.
    child.close()
# Print the final state of the child. Normally isalive() should be FALSE.
if child.isalive():
    print 'Child did not exit gracefully.'
else:
    print 'Child exited gracefully.'