编程语言
首页 > 编程语言> > python – 从pexpect捕获输出

python – 从pexpect捕获输出

作者:互联网

我遇到了pexpect问题.我试图从tralics中获取输出,这些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?

解决方法:

根据我的理解,你试图从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

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

标签:python,mathml,pexpect
来源: https://codeday.me/bug/20190625/1288079.html