gpt4 book ai didi

python - 如何为带有彩色文本的终端运行 pexpect 脚本

转载 作者:行者123 更新时间:2023-11-28 17:18:25 25 4
gpt4 key购买 nike

当我在交互式 session 中运行时,Pexpect 工作正常,但如果它有彩色文本,那么它不仅仅匹配文本,它匹配文本和 ansi 颜色。这个正则表达式非常复杂而且很大。有人可以建议我如何使用它。

例如:

而不只是寻找:

"opendaylight-user@root"

它正在寻找:

"or '\x1b[1mlogout\x1b[0m' to shutdown OpenDaylight.\r\r\n\r\n\x1b.\r\r\n
\r\n\x1b[36mopendaylight-user\x1b[0m\x1b[1m@\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("opendaylight-user@root>")
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("opendaylight-user@root>")
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[1m@\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[1m@\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("opendaylight-user@root>")

最佳答案

我通过使用 expect_exact() 而不是 expect() 得到了答案。 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[1m@\x1b[0m\x1b[34mroot\x1b[0m>")
print child.before
ex1()

关于python - 如何为带有彩色文本的终端运行 pexpect 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42849966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com