如何在Python程序中使用Mathematica函数?

时间:2012-04-23 07:57:35

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

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

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

我搜索了MathLink但是如何在Python中使用它对我来说有点模糊。

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

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

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

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

2 个答案:

答案 0 :(得分:3)

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

要从Python使用Prime,您可以运行类似:

  
    
      

kernel.ready()

    
         

0

         
      

kernel.putfunction( “素”,1)

             

kernel.putinteger(10)

             

kernel.flush()

             

kernel.ready()

    
         

1

         
      

kernel.nextpacket()

    
         

3

         
      

packetdescriptiondictionary [3]

    
         

'ReturnPacket'

         
      

kernel.getinteger()

    
         

29

  

答案 1 :(得分:3)

我找到了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-I为文件提供了执行权限。

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}

快乐!