使用pexpect和winpexpect

0 投票
1 回答
4145 浏览
提问于 2025-04-18 16:17

我有一个程序,它使用了 pexpect 这个库,需要在 Windows 和 Linux 两个系统上运行。pexpect 和 winpexpect 的接口基本上是一样的,唯一的不同在于 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

检查操作系统类型可能会更简单一些(这些信息在后续使用中可能也会有用,比如在创建 expect 会话对象时)。下面是一个实际的例子,它会根据操作系统启动合适的命令行,并根据操作系统设置我们稍后在脚本中寻找的提示符,以便识别命令是否执行完成:

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

撰写回答