如果您在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?

有帮助吗?

解决方案

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 /醪/ PRE6

更新:最后,Mathematica 8原生支持<!> quot; -script <!>;命令行选项:

http://www.wolfram.com/数学/新-在-8 /数学壳脚本/

其他提示

这是一个不需要额外帮助程序脚本的解决方案。您可以使用以下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 进行用户输入,即函数输入 InputString 不起作用。

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

假设您将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?

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

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

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

对于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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top