【问题标题】:Using pexpect and winpexpect使用 pexpect 和 winpexpect
【发布时间】:2014-09-29 19:14:16
【问题描述】:

我有一个使用 pexpect 的程序,它需要在 windows 和 linux 上运行。 pexpect 和 winpexpect 具有相同的 API,但 spawn 方法除外。在我的代码中同时支持两者的最佳方式是什么?

我的想法是这样的:

import pexpect

use_winpexpect = True

try:
    import winpexpect
except ImportError:
    use_winpexpect = False

# Much later

if use_winpexpect:
    winpexpect.winspawn()
else:
    pexpect.spawn()

但我不确定这是否可行或是否是个好主意。

【问题讨论】:

  • 目前对你帮助不大,但在 pexpect 的下一个版本中,我们将折回其中一个支持 Windows 的版本,因此两者都有一个 API .

标签: python pexpect


【解决方案1】:

检查操作系统类型(可能对下游有用的信息以及您如何创建期望会话对象)并根据此做出导入决定可能会更容易。一个实际示例,它生成适合操作系统的 shell,并基于操作系统设置我们稍后将在脚本中查找的提示,以识别命令何时完成:

# what platform is this script on?
import sys
if 'darwin' in sys.platform:
    my_os = 'osx'
    import pexpect
elif 'linux' in sys.platform:
    my_os = 'linux'
    import pexpect
elif 'win32' in sys.platform:
    my_os = 'windows'
    import winpexpect
else:
    my_os = 'unknown:' + sys.platform
    import pexpect

# now spawn the shell and set the prompt
prompt = 'MYSCRIPTPROMPT' # something we would never see in this session
if my_os == 'windows':
    command = 'cmd.exe'
    session = winpexpect.winspawn(command)
    session.sendline('prompt ' + prompt)
    session.expect(prompt) # this catches the setting of the prompt
    session.expect(prompt) # this catches the prompt itself.
else:
    command = '/bin/sh'
    session = pexpect.spawn(command)
    session.sendline('export PS1=' + prompt)
    session.expect(prompt) # this catches the setting of the prompt
    session.expect(prompt) # this catches the prompt itself.

【讨论】:

  • 是的,这就是我最终要做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
相关资源
最近更新 更多