使用pexpect和winpexpect

时间:2014-08-06 18:19:52

标签: python pexpect

我有一个使用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()

但我不确定这是否有用或者是个好主意。

1 个答案:

答案 0 :(得分:0)

检查操作系统类型(下游可能有用的信息以及创建期望会话对象的方式)可能更容易,并根据该类型做出导入决策。产生适用于操作系统的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.