【问题标题】:Capture output from pexpect从 pexpect 捕获输出
【发布时间】:2012-10-10 17:50:51
【问题描述】:

我在使用 pexpect 时遇到问题。我正在尝试从 tralics 获取输出,它读取乳胶方程并发出 MathML 表示,如下所示:

1 ~/ % tralics --interactivemath
This is tralics 2.14.5, a LaTeX to XML translator, running on tlocal
Copyright INRIA/MIAOU/APICS/MARELLE 2002-2012, Jos\'e Grimm
Licensed under the CeCILL Free Software Licensing Agreement
Starting translation of file texput.tex.
No configuration file.
> $x+y=z$
<formula type='inline'><math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><mi>x</mi>   <mo>+</mo><mi>y</mi><mo>=</mo><mi>z</mi></mrow></math></formula>
> 

所以我尝试使用 pexpect 获取公式:

import pexpect
c = pexpect.spawn('tralics --interactivemath')
c.expect('>')
c.sendline('$x+y=z$')
s = c.read_nonblocking(size=2000)
print s

输出有公式,但开头是原始输入,结尾是一些控制字符:

"x+y=z$\r\n<formula type='inline'><math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><mi>x</mi><mo>+</mo><mi>y</mi><mo>=</mo><mi>z</mi></mrow></math></formula>\r\n\r> \x1b[K"

我可以清理输出字符串,但我必须缺少一些基本的东西。有没有更简洁的方法来获取 MathML?

【问题讨论】:

    标签: python mathml pexpect


    【解决方案1】:

    据我了解,您正试图从 pexpect 获得此信息:

    <formula type='inline'><math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><mi>x</mi>   <mo>+</mo><mi>y</mi><mo>=</mo><mi>z</mi></mrow></math></formula>
    

    您可以使用正则表达式而不是“>”进行匹配,以获得预期的结果。这是最简单的例子:

    c.expect("<formula.*formula>");
    

    之后,就可以调用pexpect的match属性来访问匹配的字符串了:

    print c.match
    

    您也可以尝试不同的正则表达式,因为我发布的是一个贪婪的表达式,如果公式很大,它可能会妨碍您的执行时间。

    【讨论】:

    • 谢谢!为了完整起见,我执行c.expect("&lt;formula.*formula&gt;"),然后使用print c.match.group() 得到结果。为了准备下一个公式,我执行 `c.expect('>') 并重复。
    猜你喜欢
    • 2013-02-25
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2022-12-22
    • 1970-01-01
    相关资源
    最近更新 更多