2017-03-17 83 views
3

當我在交互式會話中運行時,Pexpect可以正常工作,但如果它具有彩色文本,那麼它不僅僅匹配文本,而是將文本與ansi顏色相匹配。這個正則表達式非常複雜和大。有人可以告訴我如何處理這件事。如何運行帶有彩色文本的終端的pexpect腳本

例如:

,而不是僅僅在尋找:

「opendaylight用戶@根」

其尋找:

「或「\ x1b [1mlogout \ x1b [0m'關閉 OpenDaylight。\ r \ r \ n \ r \ n \ x1b。\ r \ r \ n
\ r \ n \ x1b [36mopendaylight-user \ x1b [0m \ x1b [0m \ x1b [34mroot \ x1b [0m>]。

這只是表達的一部分。

import pexpect 
import os 
def ex1(): 
     os.chdir("opendaylight/distribution-karaf-0.3.4-Lithium-SR4/bin/") 
     child=pexpect.spawn("./karaf clean",cwd="/home/ubuntu/opendaylight/distribution-karaf-0.3.4-Lithium-SR4/bin/") 
     child.expect("[email protected]>") 
     print child.before 
ex1() 

錯誤

Traceback (most recent call last): 
    File "ex07.py", line 11, in <module> 
    ex1() 
    File "ex07.py", line 9, in ex1 
    child.expect("[email protected]>") 
    File "/usr/local/lib/python2.7/dist-packages/pexpect/spawnbase.py", line 321, in expect 
    timeout, searchwindowsize, async) 
    File "/usr/local/lib/python2.7/dist-packages/pexpect/spawnbase.py", line 345, in expect_list 
    return exp.expect_loop(timeout) 
    File "/usr/local/lib/python2.7/dist-packages/pexpect/expect.py", line 107, in expect_loop 
    return self.timeout(e) 
    File "/usr/local/lib/python2.7/dist-packages/pexpect/expect.py", line 70, in timeout 
    raise TIMEOUT(msg) 
    pexpect.exceptions.TIMEOUT: Timeout exceeded. 
    <pexpect.pty_spawn.spawn object at 0x7f2c5ca8ae10> 
    command: ./karaf 
    args: ['./karaf', 'clean'] 
    buffer (last 100 chars): " or '\x1b[1mlogout\x1b[0m' to shutdown  OpenDaylight.\r\r\n\r\n\x1b[36mopendaylight-user\x1b[0m\x1b[[email protected]\x1b[0m\x1b[34mroot\x1b[0m>" 
    before (last 100 chars): " or '\x1b[1mlogout\x1b[0m' to shutdown OpenDaylight.\r\r\n\r\n\x1b[36mopendaylight- user\x1b[0m\x1b[[email protected]\x1b[0m\x1b[34mroot\x1b[0m>" 
    after: <class 'pexpect.exceptions.TIMEOUT'> 
    match: None 
    match_index: None 
    exitstatus: None 
    flag_eof: False 
    pid: 20699 
    child_fd: 5 
    closed: False 
    timeout: 30 
    delimiter: <class 'pexpect.exceptions.EOF'> 
    logfile: None 
    logfile_read: None 
    logfile_send: None 
    maxread: 2000 
    searchwindowsize: None 
    delaybeforesend: 0.05 
    delayafterclose: 0.1 
    delayafterterminate: 0.1 
    searcher: searcher_re: 
    0: re.compile("[email protected]>") 
+1

我改變了。如果它沒有足夠的PLZ,讓我知道你期望什麼樣的變化 – user7369931

+0

嘗試搜索忽略[轉義碼](https://en.wikipedia.org/wiki/ANSI_escape_code) –

回答

2

我用expect_exact得到的答案(),而不是預期()。 expect()與正則表達式匹配,但expect_exact與字符串匹配。

import pexpect 
    import os 
    def ex1(): 
     os.chdir("opendaylight/distribution-karaf-0.3.4-Lithium-SR4/bin/") 
     child=pexpect.spawn("./karaf clean",cwd="/home/ubuntu/opendaylight/distribution-karaf-0.3.4-Lithium-SR4/bin/") 
     child.expect_exact("\x1b[36mopendaylight-user\x1b[0m\x1b[[email protected]\x1b[0m\x1b[34mroot\x1b[0m>") 
     print child.before 
    ex1()