从命令行调用Mathematica程序,使用命令行args,stdin,stdout和stderr

时间:2008-09-29 09:16:13

标签: command-line scripting wolfram-mathematica

如果您在foo.m中有Mathematica代码,可以使用-noprompt调用Mathematica 和-initfile foo.m (或-run "<<foo.m") 并且命令行参数在$CommandLine中可用(其中有额外的垃圾),但是有一种方法可以只有一些mathematica代码,如

#!/usr/bin/env MathKernel
x = 2+2;
Print[x];
Print["There were ", Length[ARGV], " args passed in on the command line."];
linesFromStdin = readList[];
etc.

并chmod它可执行并运行它?换句话说,如何像任何其他脚本语言(Perl,Python,Ruby等)一样使用Mathematica?

6 个答案:

答案 0 :(得分:10)

MASH - Mathematica Scripting Hack - 将会这样做。

从Mathematica版本6开始,以下perl脚本就足够了:

http://ai.eecs.umich.edu/people/dreeves/mash/mash.pl

对于以前的Mathematica版本,需要一个C程序:

http://ai.eecs.umich.edu/people/dreeves/mash/pre6

更新:最后,Mathematica 8使用“-script”命令行选项原生支持:

http://www.wolfram.com/mathematica/new-in-8/mathematica-shell-scripts/

答案 1 :(得分:5)

这是一个不需要额外帮助程序脚本的解决方案。您可以使用以下shebang直接调用Mathematica内核:

#!/bin/sh
exec <"$0" || exit; read; read; exec /usr/local/bin/math -noprompt "$@" | sed '/^$/d'; exit
(* Mathematica code starts here *)
x = 2+2;
Print[x];

shebang代码跳过脚本的前两行,并将其余部分作为标准输入提供给Mathematica内核。 sed 命令会删除内核生成的空行。

这种黑客并不像MASH那样多才多艺。因为从 stdin 读取Mathematica代码,所以不能使用 stdin 进行用户输入,即函数InputInputString不起作用。< / p>

答案 2 :(得分:4)

尝试
-initfile filename
并将exit命令放入程序

答案 3 :(得分:4)

假设您将Mathematica二进制文件添加到〜/ .profile中的PATH环境变量中,

export PATH=$PATH:/Applications/Mathematica.app/Contents/MacOS

然后你只需在Mathematica脚本中写下这个shebang行。

#!/usr/bin/env MathKernel -script

现在你可以点击你的脚本。

$ cat hello.ma
#!/usr/bin/env MathKernel -script

Print["Hello World!"]

$ chmod a+x hello.ma
$ ./hello.ma
"Hello World!"

使用Mathematica 8.0进行测试。

小错误:Mathematica在Windows和Mac OS X中用引号括起Print [s],但不包括Linux。 WTF?

答案 4 :(得分:2)

我找到了另一个对我有用的解决方案。

将代码保存在.m文件中,然后像下面这样运行:MathKernel -noprompt -run“&lt;

这是链接:http://bergmanlab.smith.man.ac.uk/?p=38

答案 5 :(得分:1)

对于mathematica 7

$ cat test.m
#!/bin/bash
MathKernel -noprompt -run < <( cat $0| sed -e '1,4d' )  | sed '1d'
exit 0
### code start Here ... ###
Print["Hello World!"]
X=7
X*5

用法:

$ chmod +x test.m

$ ./test.m
"Hello World!"

7
35