使用Python处理另一个脚本中的交互式脚本

3
我有一个交互式的shell脚本,现在我正在创建一些自动化来向这个脚本提供输入。这个自动化是使用Python完成的。例如,
当shell脚本等待输入时,比如“域名是什么?”,Python应该能够提供输入并按下回车键。
请提供解决这种情况的解决方案,并附带一些示例。

我几天前就在思考这个问题,但完全没有头绪... - wong2
3
请提供一个问题(http://stackoverflow.com/questions/how-to-ask)。 - Lesmana
你想运行一个包含交互提示的shell脚本,但是你希望Python为你填写这些内容,对吗? - Skurmedel
1个回答

4

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

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.'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接