首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用pexpect和winpexpect

使用pexpect和winpexpect
EN

Stack Overflow用户
提问于 2014-08-07 02:19:52
回答 1查看 3.4K关注 0票数 0

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

我是这样想的:

代码语言:javascript
复制
import pexpect

use_winpexpect = True

try:
    import winpexpect
except ImportError:
    use_winpexpect = False

# Much later

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

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

EN

回答 1

Stack Overflow用户

发布于 2015-05-30 03:13:18

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

代码语言:javascript
复制
# 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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25167382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档