我将如何使用 Python 中的 subprocess 模块来启动 MAPLE 的命令行实例来提供输出并将输出返回给主代码?例如我想:
X = '1+1;'
print MAPLE(X)
返回“2”的值。
我见过的最好的是围绕 MAPLE 命令的 SAGE 包装器,但我不想安装和使用 SAGE 的开销来实现我的目的。
我将如何使用 Python 中的 subprocess 模块来启动 MAPLE 的命令行实例来提供输出并将输出返回给主代码?例如我想:
X = '1+1;'
print MAPLE(X)
返回“2”的值。
我见过的最好的是围绕 MAPLE 命令的 SAGE 包装器,但我不想安装和使用 SAGE 的开销来实现我的目的。
使用 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 的连接以供将来计算。
这是一个如何使用命令行程序进行交互式 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..
唯一的问题是它非常脆弱,而且是一个反复试验的过程,以确保您没有发送任何错误的输入并处理程序可能产生的所有不同输出。