![](/img/trans.png)
[英]Capture output from C program on stdout using Python subprocess? Pexpect?
[英]Capture output from 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
你也可以嘗試不同的正則表達式,因為我發布的那個是貪婪的,如果公式很大,它可能會妨礙你的執行時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.