3

我将如何使用 Python 中的 subprocess 模块来启动 MAPLE 的命令行实例来提供输出并将输出返回给主代码?例如我想:

X = '1+1;'
print MAPLE(X)

返回“2”的值。

我见过的最好的是围绕 MAPLE 命令的 SAGE 包装器,但我不想安装和使用 SAGE 的开销来实现我的目的。

4

3 回答 3

3

尝试“交互式”地驱动子进程往往会遇到子进程做一些缓冲的问题,这会阻塞事情。

这就是为什么我建议使用pexpect(除了 Windows 之外的任何地方:Windows上的wexpect),它正是为此目的而设计的——让你的程序模拟(从子进程的角度)一个人类用户输入输入/命令并查看结果在终端/控制台。

于 2010-01-13T04:01:04.370 回答
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 的连接以供将来计算。

于 2010-01-13T18:29:46.837 回答
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..

唯一的问题是它非常脆弱,而且是一个反复试验的过程,以确保您没有发送任何错误的输入并处理程序可能产生的所有不同输出。

于 2010-01-13T18:02:57.157 回答