【问题标题】:Handling an interactive script from another script , using python使用 python 处理来自另一个脚本的交互式脚本
【发布时间】:2011-05-17 12:50:11
【问题描述】:

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

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

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

【问题讨论】:

  • 我几天前就在想这个问题,完全不知道......
  • 请提供question
  • 你想运行 shell 脚本,一个包含交互式提示的脚本,但是你想让 Python 为你填充这些?对吗?

标签: python


【解决方案1】:

期待: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.'

【讨论】:

    猜你喜欢
    • 2012-12-31
    • 2017-08-26
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多