2

I encounter the problem that I can't save any output from Mathematica script. Here is a minimal example.

test.m

Export["/home/my_home_folder/file.txt", "hello world"]

I run the script with

math -script test.m

and the output file is not produced. Instead of math I've also tried MathematicaScript and wolframscript -f test.m, they hadn't work either.

Interactively, i.e. running math from the terminal and executing the same Export command, everything works just fine. I run the script remotely using ssh on a Linux machine.

Is there a way to fix this or any alternative way of saving the data from the script mode?

EDIT.

OK, I resolved the problem and it was pretty dumb. I used Mathematica as an editor and my cells was of the "Input" type, but it should have been of the "Code" type, otherwise, it doesn't work.

Here is the non-working version of the code as it is viewed by Notepad:

(* ::Package:: *)

(* ::Input:: *)
(*Export["/home/my_home_folder/file.txt","hello world"]*)

And here is the working one:

(* ::Package:: *)

(* ::Code:: *)
(*Export["/home/my_home_folder/file.txt","hello world"]*)

1 Answers1

1

This is what I usually do for scripting (this works in a cluster too). Say I want to write script that depends on one argument. Then I define script.m to be

cmds=Drop[$CommandLine,3];

param = cmds[[1]];

(*Do stuff with param*)
result = param;
path = "/path/to/my/folder/result.txt";
(*End of stuff*)

Export[path, result];
WriteString["stdout", "Results exported to "<>path<>"\n"];

Quit[];

Then if you call it with

math -run "<<script.m" "Write this!"

It will write Write this! to the file /path/to/my/file/result.txt. This works fine for me, even on a cluster. Recall that when a job gets evaluated on a cluster, it's evaluated on a machine different from the login node. So Directory[] will give a different output.

Also, in most clusters you can redirect stdout to some file. In slurm for example you have to set up

#!/bin/bash
#SBATCH --chdir=/path/to/my/folder
#<Possibly other options>
#...

math -run "<<script.m" "Write this!"

But you may have a different cluster manager.

MannyC
  • 810
  • 5
  • 15
  • Thank you for your extended answer! I kept trying and finally resolved the problem. It was really stupid (see the edit). – quantum_dog Apr 02 '20 at 10:40