我如何使用Python中的子进程模块启动MAPLE的命令行实例来提供并将输出返回到主代码?例如,我想:
X = '1+1;'
print MAPLE(X)
返回“2”的值。
我见过的最好的是围绕MAPLE命令的SAGE包装器,但是我不想为了我的目的而安装和使用SAGE的开销。
答案 0 :(得分:3)
尝试以“交互方式”驱动子流程时,经常遇到子进程执行缓冲的问题,这会阻塞事物。
这就是为什么出于这样的目的,我建议改为使用pexpect(在Windows上除了Windows:wexpect之外的所有地方),这是为了这个目的而设计的 - 让您的程序模拟(从子流程的角度来看)人类用户键入输入/命令并在终端/控制台上查看结果。
答案 1 :(得分:3)
使用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的连接,以便将来进行计算。
答案 2 :(得分:0)
以下是如何使用命令行程序执行交互式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..
唯一的问题是它非常脆弱,并且是一个试错过程,以确保您不会发送任何错误输入并处理程序可能产生的所有不同输出。