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

时间:2020-03-06 14:52:03  来源:igfitidea点击:

如果我们在foo.m中有Mathematica代码,则可以使用-noprompt来调用Mathematica。 并带有-initfile foo.m (或者-run" << foo.m"`)
和命令行参数可以在$ CommandLine中使用(其中有多余的垃圾),但是有一种方法可以只包含一些数学代码,例如

#!/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?

解决方案

尝试
-initfile文件名
并将exit命令放入程序中

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/

这是一种不需要其他帮助程序脚本的解决方案。我们可以使用以下shebang来直接调用Mathematica内核:

#!/bin/sh
exec <"##代码##" || 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那样通用。由于Mathematica代码是从stdin中读取的,因此我们不能将stdin用于用户输入,即Input和InputString函数不起作用。