我有一个使用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()但我不确定这是否可行,或者这是一个好主意。
发布于 2015-05-30 03:13:18
检查OS类型(可能对下游有用的信息,以及如何创建expect session对象)并基于此做出导入决策可能更容易。这是一个实际的示例,它生成适合操作系统的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.https://stackoverflow.com/questions/25167382
复制相似问题