【问题标题】:How to use Mathematica functions in Python programs? [closed]如何在 Python 程序中使用 Mathematica 函数? [关闭]
【发布时间】:2012-04-23 07:57:35
【问题描述】:

我想知道如何从 Python 调用 Mathematica 函数。

我很欣赏一个例子,例如,使用 Mathematica 函数 Prime

我搜索过MathLink,但如何在 Python 中使用它对我来说有点晦涩。

我尝试使用名为 pyml 的 Mathematica-Python 库,但没有成功,可能是因为这个库看起来很旧(教程中说 Mathematica 2 或 3)。 p>

尝试在 Wolfram/Mathematica/8.0/SystemFiles/Links/Python 中编译源代码,但在使用 python 2.6 时出现了几个错误(文档说应该只适用于 python 2.3)。

Pythonika 很有趣,但是,看起来只是在 Mathematica 笔记本中使用,我想编写调用 Mathematica 函数的 .py 文件。

那么,有人知道使用 Mathematica 函数编写 python 程序的好方法,可以给我一个例子吗?

【问题讨论】:

  • 是否有特定的 Mathematica only 函数需要调用?如果没有,很可能另一个库实现了您所追求的。例如,numpy 是一个广泛的数学库,适用于 Python
  • 是一个有趣的观点,但是,我想要我知道 Mathematica 中可用的功能并使用它。所以,在我看来,numpy 和 scypy 在这方面的能力有点落后。
  • 我找到了解决方案,并将其发布为答案。我很快就会接受它。
  • 这是交叉发布的here

标签: python unix wolfram-mathematica mathematica-8 mathlink


【解决方案1】:

您可以使用 Python MathLink 模块(您在 .../SystemFiles/Links/Python 中找到的源代码)在 Python 中调用 Mathematica 函数,但您需要编辑几个设置文件才能启动并运行它(support@wolfram.com 应该能够为您提供帮助)。

要在 Python 中使用 Prime,您需要运行以下命令:

kernel.ready()

0

kernel.putfunction("Prime",1)

kernel.putinteger(10)

kernel.flush()

kernel.ready()

1

kernel.nextpacket()

3

数据包描述字典[3]

'返回包'

kernel.getinteger()

29

【讨论】:

  • 看起来我差不多是nikko^^。几乎所有东西都运行了,但最后的命令中断了。你能看看这个pastebin link 并告诉我发生了什么吗?
  • 感谢您对 nikko 的帮助。
  • 看起来数据包的返回方式与我的不同。尝试使用 kernel.getstring() 来查看返回字符串是什么(抱歉,btw 响应迟了)你可能会得到类似的东西: >>> kernel.getstring() 'Out[1]= ' 之后你可以再次运行 kernel.nextpacket() 并且应该能够捕获整数
【解决方案2】:

我找到了solution

步骤:

1-创建一个名为 runMath 的脚本,其内容为:

#!/usr/local/bin/MathematicaScript -script

value=ToExpression[$ScriptCommandLine[[2]]];

(*The next lime prints the script name.*)
(*Print[$ScriptCommandLine[[1]]];*)

Print[value];

2-我给了文件执行权限。

sudo chmod +x runMath

3-将文件移动到执行路径

sudo mv runMath /usr/bin/

4-创建了一个名为 run 的新脚本,其内容为:

#!/usr/bin/python
from subprocess import *
from sys import *

command='/usr/bin/runMath'
parameter=argv[1]

call([command,parameter])

5-移动到执行路径

sudo mv run /usr/bin

6-最后,测试一下:

$run Prime[100]
541

$run 'Sum[2x-1,{x,1,k}]'
k^2

$run Integrate[Log[x],x]
-x + x*Log[x]

$run 'Zeta[2]'
Pi^2/6

您可以使用或不使用'。带空格的命令需要'

$run 'f[n_] := f[n] = f[n - 1] + f[n - 2]; f[1] = f[2] = 1; Table[f[n],{n,5}]'
{1, 1, 2, 3, 5}

快乐!

【讨论】:

  • 能够通过标准输入管道输入的主题变体:Print[ToExpression[Import["!cat", "string"]]] (注意:Input[] 和 InputString[] 停止在换行符和 OpenRead["stdin"] 失败)
猜你喜欢
  • 1970-01-01
  • 2011-09-24
  • 2020-12-14
  • 2020-04-09
  • 1970-01-01
  • 2012-01-11
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多