通过 Python 获取 MAPLE 的输出
如何使用 Python 中的 subprocess 模块启动 MAPLE 的命令行实例以将输出提供并返回到主代码?例如我想:
X = '1+1;'
print MAPLE(X)
返回“2”的值。
我见过的最好的方法是围绕 MAPLE 命令的 SAGE 包装器,但我不想为了我的目的而安装和使用 SAGE 的开销。
How would I use the subprocess module in Python to start a command line instance of MAPLE to feed and return output to the main code? For example I'd like:
X = '1+1;'
print MAPLE(X)
To return the value of "2".
The best I've seen is a SAGE wrapper around the MAPLE commands, but I'd like to not install and use the overhead of SAGE for my purposes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试“交互地”驱动子进程常常会遇到子进程进行一些缓冲的问题,这会阻止事情发生。
这就是为什么出于这样的目的,我建议改为使用 pexpect (除了 Windows 之外的任何地方: wexpect(Windows 上)),正是为此目的而设计的 - 让您的程序进行模拟(从子流程的观点)人类用户键入输入/命令并在终端/控制台上查看结果。
Trying to drive a subprocess "interactively" more often than not runs into issues with the subprocess doing some buffering, which blocks things.
That's why for such purposes I suggest instead using pexpect (everywhere but Windows: wexpect on Windows), which is designed exactly for this purpose -- letting your program simulate (from the subprocess's viewpoint) a human user typing input/commands and looking at results at a terminal/console.
根据 Alex Martelli 的提示(谢谢!),我对我的问题给出了明确的答案。在此发布,希望其他人可能会发现有用:
需要对输出进行解析,因为 MAPLE 认为有必要将长输出分解为多行。这种方法的优点是保持对 MAPLE 开放的连接以供将来的计算使用。
Using the tip from Alex Martelli (thank you!), I've came up with an explicit answer to my question. Posting here in hopes that others may find useful:
The parsing of the output is needed as MAPLE deems it necessary to break up long outputs onto many lines. This approach has the advantage of keeping a connection open to MAPLE for future computation.
下面是如何使用命令行程序进行交互式 IO 的示例。我使用了类似的东西来构建基于
ispell
命令行实用程序的拼写检查器:唯一的问题是它非常脆弱,并且需要一个试错过程来确保您不会发送任何错误的输入以及处理程序可能产生的所有不同输出。
Here's an example of how to do interactive IO with a command line program. I used something similar to build a spell checker based on the
ispell
command line utility:The only problem with this is that it's very brittle and a trial-and-error process to make sure you're not sending any bad input and handling all the different output the program could produce.