在Mac OS X上,从命令行以批处理模式运行Mathematica

6
我想开始为我的Mathematica程序编写一些单元测试,并使用一些Makefiles从命令行控制所有内容。
看起来Mathematica 可以从命令行运行,但我找不到任何关于在Mac OS X上入门的基本说明 - 有人以前做过这个吗?

更新:

创建一个像这样的测试文件:

Print["你好"];
x:= 1;
y = x + 1;
z = y + 1;
Print["y="ToString@y];
Print["z="ToString@z];
Quit[];

然后使用以下命令运行它:

/Applications/Mathematica.app/Contents/MacOS/MathKernel -noprompt < test.m

这是我能找到的最接近批处理的东西。但输出看起来不太美观,每行脚本都会添加换行符!

"hello"
"y=2"
"z=3"

这是我能得到的最接近仍能向控制台输出信息的脚本吗?我只使用Mathematica 6,但我希望这不会有影响。


你看过 mash 吗?http://ai.eecs.umich.edu/people/dreeves/mash/ - Pillsy
3个回答

3
这样,最终输出的结果就像我期望的那样:
/Applications/Mathematica.app/Contents/MacOS/MathKernel -noprompt -run "<<test.m"

我想这是有道理的。将以下内容添加到我的.bash_profile文件中,可以轻松执行(例如:mma test.m):

mma () { /Applications/Mathematica.app/Contents/MacOS/MathKernel -noprompt -run "<<$1" ; }

还可以参考dreeves的mash Perl脚本,它可能比这种方法更有优势。


2

经过一些试验,我发现可以从命令行启动/Applications/Mathematica.app/Contents/MacOS/MathKernel。然而,它似乎不接受通常的-h--help命令行标志。


0

感谢 Pillsy 和 Will Robertson 提供的 MASH 插件!以下是相关的 StackOverflow 问题:如何从命令行调用 Mathematica 程序,并传递命令行参数、标准输入、标准输出和标准错误输出

如果您不使用 MASH,您可能希望使用以下由 MASH 定义的实用程序函数。例如,标准打印函数会在字符串周围打印引号——这通常不是脚本所需的。

ARGV = args = Drop[$CommandLine, 4];         (* Command line args.            *)
pr = WriteString["stdout", ##]&;             (* More                          *)
prn = pr[##, "\n"]&;                         (*  convenient                   *)
perr = WriteString["stderr", ##]&;           (*   print                       *)
perrn = perr[##, "\n"]&;                     (*    statements.                *)
EOF = EndOfFile;                             (* I wish mathematica            *)
eval = ToExpression;                         (*  weren't so damn              *)
re = RegularExpression;                      (*   verbose!                    *)
read[] := InputString[""];                   (* Grab a line from stdin.       *)
doList[f_, test_] :=                         (* Accumulate list of what f[]   *)
  Most@NestWhileList[f[]&, f[], test];       (*  returns while test is true.  *)
readList[] := doList[read, #=!=EOF&];        (* Slurp list'o'lines from stdin *)

要使用MASH,只需获取那个Perl文件mash.pl,然后制作以下test.m文件:

#!/usr/bin/env /path/to/mash.pl

prn["hello"];
x := 1;
y = x+1;
z = y+1;
prn["y=", y];
prn["z=", z];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接