簡體   English   中英

使用pexpect和winpexpect

[英]Using pexpect and winpexpect

我有一個使用pexpect的程序,該程序需要在Windows和Linux上運行。 除了spawn方法外,pexpect和winpexpect具有相同的API。 在我的代碼中同時支持兩者的最佳方法是什么?

我在考慮以下思路:

import pexpect

use_winpexpect = True

try:
    import winpexpect
except ImportError:
    use_winpexpect = False

# Much later

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

但是我不確定這是否可行還是一個好主意。

檢查OS類型(對於下游可能有用的信息以及如何創建期望的會話對象)可能會更容易,並據此做出導入決定。 一個實際的示例將生成適合於OS的外殼,並根據OS設置提示,我們稍后將在腳本中查找以識別命令何時完成:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM