如何使用Python中的子进程模块启动MAPLE的命令行实例,以便将输出提供给主代码并返回给主代码?例如,我希望:
X = '1+1;'
print MAPLE(X)返回"2“的值。
我所见过的最好的就是围绕MAPLE命令的SAGE包装器,但是我不想安装和使用SAGE的开销来达到我的目的。
发布于 2010-01-14 02:29:47
使用Alex Martelli的建议(谢谢!),我已经对我的问题给出了明确的答案。在这里发帖,希望其他人能找到有用的:
import pexpect
MW = "/usr/local/maple12/bin/maple -tu"
X = '1+1;'
child = pexpect.spawn(MW)
child.expect('#--')
child.sendline(X)
child.expect('#--')
out = child.before
out = out[out.find(';')+1:].strip()
out = ''.join(out.split('\r\n'))
print out由于MAPLE认为有必要将长输出分解为多行,因此需要对输出进行解析。这种方法的优点是保持对MAPLE的连接开放,以便将来进行计算。
发布于 2010-01-13 12:01:04
试图“交互地”驱动一个子进程时,经常会遇到子进程进行缓冲的问题,这会阻塞一些事情。
这就是为什么我建议使用pexpect (除了Windows以外的任何地方:Windows上的wexpect ),它就是为此目的而设计的--让您的程序(从子进程的角度)模拟人类用户在终端/控制台键入输入/命令并查看结果。
发布于 2010-01-14 02:02:57
下面是一个如何使用命令行程序进行交互式IO的示例。我使用类似的方法构建了一个基于ispell命令行实用程序的拼写检查器:
f = popen2.Popen3("ispell -a")
f.fromchild.readline() #skip the credit line
for word in words:
f.tochild.write(word+'\n') #send a word to ispell
f.tochild.flush()
line = f.fromchild.readline() #get the result line
f.fromchild.readline() #skip the empty line after the result
#do something useful with the output:
status = parse_status(line)
suggestions = parse_suggestions(line)
#etc..唯一的问题是,它非常脆弱,并且是一个反复尝试的过程,以确保您不会发送任何错误的输入,并处理程序可能产生的所有不同输出。
https://stackoverflow.com/questions/2053231
复制相似问题