4
$\begingroup$

I am working on a project that requires some calculations to be done in Mathematica. I don't know Wolfram language and I don't have the time to learn it (I am using a 30-day trial) so I have a python program that is generating a lot of .nb files.

What I would like to do would be to be able to run this .nb files from command line and then save their outuput to a .txt, .png, .jpg, any format I can work with without having to open Mathematica, run the notebook and grab the data.

The output of the notebook file is given by some calls to Print and also the following command

Show[Graphics[...], Graphics[...], 

 Graphics[...], Graphics[...], Axes -> False]

The ... were added for this question.

I am hoping for a command like:

mathematica-command -options file.nb > output_file

I have Windows 8 and the latest Mathematica.

Thanks in advance.

$\endgroup$

closed as off-topic by Yves Klett, bobthechemist, ybeltukov, m_goldberg, Karsten 7. Sep 12 '14 at 19:46

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question cannot be answered without additional information. Questions on problems in code must describe the specific problem and include valid code to reproduce it. Any data used for programming examples should be embedded in the question or code to generate the (fake) data must be included." – Yves Klett, bobthechemist, ybeltukov, m_goldberg, Karsten 7.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ Related / dupe: mathematica.stackexchange.com/q/13055/131 or mathematica.stackexchange.com/q/30310/131. But basically telling us that you will not learn WL/ Mathematica may not really motivate potential answers. In any case, you should provide more information on your intended workflow and the notebook content. $\endgroup$ – Yves Klett Sep 12 '14 at 14:35
  • $\begingroup$ @YvesKlett I have seen your links and I still don't see how I am supposed to save the output. I said that I won't learn Mathematica because surely what I am doing from within Python can be done with Mathematica but I don't have time to learn that much. Also, I cannot show any code besides the one I added in the edited question. The Mathematica code I am using was kindly given to me by a friend who does not allow me to share it. $\endgroup$ – user1790813 Sep 12 '14 at 15:38
  • $\begingroup$ O.k. - difficult call. It would be simpler if you let Mathematica Export the graphics. But without any code helping you is really difficult. $\endgroup$ – Yves Klett Sep 12 '14 at 15:55
  • $\begingroup$ Ok that would fix the problem with the image, but I really need the numbers in those Prints I mentioned. $\endgroup$ – user1790813 Sep 12 '14 at 15:58
  • $\begingroup$ The same applies for the numbers - Exporting them in a useful format would be straightforward. Otherwise the whole setup will be a real contortion and not a Mathematica. $\endgroup$ – Yves Klett Sep 12 '14 at 16:06
4
$\begingroup$

some time ago I had a similar problem and the old code still seems to work:

rolf@merkur /cygdrive/c/nbfiles
$ "/cygdrive/c/Program Files/Wolfram Research/Mathematica/10.0/math" < nb2pdftest.m > nb2pdftest.out

where nb2pdftest.m is

(* Author: Rolf Mertig *)
(* Organization: GluonVision GmbH *)
(* Copyright: GluonVision GmbH *)
(* Date: 2006-06-06 *)

(* Documentation: Evaluate from a command line a previously saved notebook,
                  save the evaluated notebook, and print it to the
                  default printer (which can be PDFCreator with 'Auto-save'
                  option on; the files are in the directory as set in the
                  PDFCreator option tab).

   For a sample usage see the Example section at the end of this file.

*)

(* Limitations: Windows only for the moment. *)

(* Version: 1.0 *)

(* Mathematica version needed: 5.0 or newer *)

(* Comments: This is more complicated than it should be ... *)
(*           Maybe the "Pause[1]" pauses have to be bigger for larger
             notebooks ?
*)


(* ************************************* *)

(* This code should not be run from the FrontEnd ... : *)
If[$FrontEnd =!= Null,
   Print["This program should be run from the Kernel, not from a FrontEnd."] ,
(* ELSE *)


BeginPackage["NB2PDF`"];

$Debug::usage="If set to True debugging messages are printed."; ;


NB2PDF::usage="NB2PDF[nbfile] evaluates the notebook nbfile and prints it to the default printer. If the default printer is, e.g., PDFCreator (from https://sourceforge.net/projects/pdfcreator), with 'Auto-save' option on, the filename used for printing is the date, and the directory used for auto-save the one indicated in the 'Auto-save' dialog." ;

NBOutToken::usage="NBOutToken is an option for NB2PDF. Its setting determines the string token added before the .nb starting filename. The resulting string is used as name for the evaluated saved notebook.";

Begin["`Private`"];

$Debug = True;

Options[NB2PDF] = {NBOutToken -> "_Evaluated"};

NB2PDF[nb_String /; StringMatchQ[nb, "*.nb", IgnoreCase-> True],
       opts___?OptionQ ] :=
       nbtopdf[Get[nb], nb, opts] /; FileNames[nb] =!= {};

nbtopdf[nbin_Notebook, nbfilename_String, opts___?OptionQ] :=
        Module[{(*nb, nbtmp, nt, nbfout*)},

nbtmp = $TemporaryPrefix <> StringJoin @@ Map[ToString, Date[] // Round] <>".txt";
nbtmp = StringReplace[nbtmp, "\\" -> "\\\\"];
nbtoken = NBOutToken /. {opts} /. Options[NB2PDF];
nbfout = StringInsert[nbfilename, nbtoken, -4];
(* in order to tell the FE that the notebook really exists we need to
   create something on disk. If this is not done a strange FE-dialog
   appears ...
*)
If[FileNames[nbfout] === {}, Export[nbfout,""]];

(* we need JLink *)
Needs["JLink`"];

JLink`InstallJava[];

(* this uses the FrontEnd as a service, in the background *)
JLink`UseFrontEnd[


(*
nt = Insert[nbin /. (WindowTitle->_):> Sequence[],
              (WindowTitle -> nbfout), -1];

Print["WindowTitle option of nt ", Options[nt,WindowTitle]] /; $Debug;
*)
nt = nbin;

(* add a final temporary cell and open the notebook : *)
nb = NotebookPut @ Insert[nt,
       Cell[ "Export[\"" <> nbtmp <>
             "\"," <> ToString[Date[]]<> ",\"Text\"];", "Input"], {1,-1}];

Print["Head  of nb = ", Head[nb]] /; $Debug;


(* Put a cell at the end which will serve as a terminating condition *)

SelectionMove[nb, Before, Notebook];
SelectionMove[nb,All,Notebook];
(* Evaluate everything. Attention: the notebook should terminate ... *)
SelectionEvaluate[nb];

Print["starting While "] /;$ Debug;

(* This is the tricky part:
   Since there are really two programs, the FrontEnd and the Kernel,
   we have to tell the kernel to wait for the FrontEnd to finish
   the evaluation of the notebook.
   We put the kernel evaluator in a While - loop until the last
   cell of the original notebook is evaluated (which cannot be done
   somehow with a kernel value or another FrontEnd-action, so we
   resume to writing a temporary file to disk and check if it there ...
*)

While[ ($filetype = FileType[nbtmp]) =!= File,
           Print["While waiting: ",  $filetype] /;$ Debug;
       Pause[1] ];

Print["finished While "] /;$ Debug;

(* at this point we are sure that everything is finished and the
   extra cell as well as the temporary file are removed easily:
*)
SelectionMove[nb,After,Notebook]; SelectionMove[nb,Previous,Cell];
DeleteFile[nbtmp];
Pause[1]; (* seems to be necessary *)
NotebookDelete[nb];
Pause[1]; (* seems to be necessary *)
NotebookSave[nb, nbfout, Interactive -> False];
fsizecheck = fsizecheck2 = 0;

While[fsizecheck =!= fsizecheck2 || fsizecheck === 0,
      fsizecheck = FileByteCount[nbfout];
Print["fsizecheck = ",fsizecheck] /; $Debug;
      Pause[1];
      fsizecheck2 = FileByteCount[nbfout];
     ];

Pause[1];
(* print the easy way: (this could be more elaborate, with options, etc.) *)
(* one could also use NETLink in order to manage the default printer ... *)

NotebookPrint[nb];
(* it might take more than one second for the PDF file to show up in the
   default save-directory of PDFCreator
*)
Pause[1];

];
];

End[];

EndPackage[];
];

(* ******************************************************* *)
(* ******************************************************* *)

(* EXAMPLE:  *)

(* ******************************************************* *)

(* Example usage:
   Uncomment the instruction below and adapt to your needs and run
   this file from the command line like this:
math < NB2PDF.m > NB2PDF.out

   The evaluated notebook will be C:\\nbfiles\\samplentebook_Evaluated.nb
   and the PDF file will be named by the current date and found in the
   directory as indicated in the PDFCreator option settings.
*)

NB2PDF["C:\\nbfiles\\samplenotebook.nb"]

and samplenotebook.nb is

(* Content-type: application/vnd.wolfram.mathematica *)

(*** Wolfram Notebook File ***)
(* http://www.wolfram.com/nb *)

(* CreatedBy='Mathematica 10.0' *)

(*CacheID: 234*)
(* Internal cache information:
NotebookFileLineBreakTest
NotebookFileLineBreakTest
NotebookDataPosition[       158,          7]
NotebookDataLength[      1105,         44]
NotebookOptionsPosition[       836,         30]
NotebookOutlinePosition[      1210,         46]
CellTagsIndexPosition[      1167,         43]
WindowFrame->Normal*)

(* Beginning of Notebook Content *)
Notebook[{
Cell[BoxData[
 RowBox[{"Plot3D", "[",
  RowBox[{
   RowBox[{"Sin", "[",
    RowBox[{"x", "  ", "y"}], " ", "]"}], ",",
   RowBox[{"{",
    RowBox[{"x", ",", "0", ",", "12"}], "}"}], ",",
   RowBox[{"{",
    RowBox[{"y", ",", "0", ",", "12"}], "}"}]}], "]"}]], "Input"]
},
WindowSize->{767, 851},
WindowMargins->{{Automatic, -1898}, {Automatic, 96}},
Magnification:>1.9 Inherited,
FrontEndVersion->"10.0 for Microsoft Windows (64-bit) (July 1, 2014)",
StyleDefinitions->"Default.nb"
]
(* End of Notebook Content *)

(* Internal cache information *)
(*CellTagsOutline
CellTagsIndex->{}
*)
(*CellTagsIndex
CellTagsIndex->{}
*)
(*NotebookFileOutline
Notebook[{
Cell[558, 20, 274, 8, 57, "Input"]
}
]
*)

(* End of internal cache information *)
$\endgroup$
  • $\begingroup$ I am preparing to delete this closed question in the course of routine clean-up. Is there anything here that you feel should be preserved for posterity? $\endgroup$ – Mr.Wizard Jan 18 '16 at 1:22
  • $\begingroup$ go ahead. I copied it for myself. $\endgroup$ – Rolf Mertig Jan 18 '16 at 8:02
  • $\begingroup$ Alternatively you could edit the post and vote to reopen? That's more the direction I was hoping to nudge you in, but I also thought perhaps a new question and self-answer would be more structured. $\endgroup$ – Mr.Wizard Jan 18 '16 at 13:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.