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

dre*_*ves 17 scripting command-line wolfram-mathematica

如果在foo.m中有Mathematica代码,Mathematica可以用-noprompt-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.
Run Code Online (Sandbox Code Playgroud)

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

dre*_*ves 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/


sak*_*kra 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];
Run Code Online (Sandbox Code Playgroud)

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

这种黑客并不像MASH那样多才多艺.因为从stdin读取Mathematica代码,所以不能将stdin用于用户输入,即函数InputInputString不起作用.


mca*_*dre 5

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

export PATH=$PATH:/Applications/Mathematica.app/Contents/MacOS
Run Code Online (Sandbox Code Playgroud)

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

#!/usr/bin/env MathKernel -script
Run Code Online (Sandbox Code Playgroud)

现在您可以对脚本进行点斜线处理。

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

Print["Hello World!"]

$ chmod a+x hello.ma
$ ./hello.ma
"Hello World!"
Run Code Online (Sandbox Code Playgroud)

用 Mathematica 8.0 测试。

小错误:Mathematica 在 Windows 和 Mac OS X 中用引号将 Print[s] 括起来,但在 Linux 中则不然。跆拳道?