简体   繁体   English

捕获pexpect的输出

[英]Capture output from pexpect

I am having trouble with pexpect . 我遇到了pexpect I'm trying to grab output from tralics which reads in latex equations and emits the MathML representation, like this: 我试图从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>
> 

So I try to get the formula using pexpect: 所以我尝试使用pexpect获取公式:

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

The output has the formula, but with the original input at the beginning and some control chars at the end: 输出具有公式,但开头的原始输入和结尾的一些控制字符:

"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"

I can clean the output string, but I must be missing something basic. 我可以清理输出字符串,但我必须遗漏一些基本的东西。 Is there a cleaner way to get the MathML? 有没有更简洁的方法来获得MathML?

From what I understand you are trying to get this from pexpect: 根据我的理解,你试图从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>

You can use a regexp instead of ">" for the matching in order to get the expected result. 您可以使用正则表达式而不是“>”进行匹配,以获得预期结果。 This is the easiest example: 这是最简单的例子:

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

After that, you can access the matched string by calling the match attribute of pexpect: 之后,您可以通过调用pexpect的match属性来访问匹配的字符串:

print c.match

You might also try different regexps, due to the fact that the one I posted is a greedy one and it might hinder your execution time if the formulas are big. 你也可以尝试不同的正则表达式,因为我发布的那个是贪婪的,如果公式很大,它可能会妨碍你的执行时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM