1
$\begingroup$

For debugging purposes, I wrote a function which should log the error message to a file. It does not work and I cannot see why this is the case. Here is the function:

execFailureQ[expr_] := Head[expr] == "execFailure";

safeExec[expr_, OptionsPattern[]] := Module[{res, err, logF, quitCode},
   res = EvaluationData[Evaluate[expr]];
   If[res["Success"], Return[res["Result"]]];
   err = StringRiffle[ToString /@ res["Messages"]];
   logF = OptionValue["logFile"];
   If[logF != None, WriteString[logF, err <> "\n"]];
   quitCode = OptionValue["quitCode"];
   If[quitCode != None, Quit[quitCode]];
   Return[execFailure[err]];
];
SetAttributes[safeExec, HoldFirst];
Options[safeExec] = {"logFile" -> None, "quitCode" -> None};

In the script, it is used like this:

logFile = OpenWrite["test.log"];
SetOptions[safeExec, "logFile"->logFile, "quitCode"->1];
safeExec[Export["wrong?file*name.xlsx", JuliaSetPlot[0.365 - 0.37 I]]];
WriteString[logFile, "Done.\n"];

When I save the last four lines above in a file "test.m" and run it via

"C:\Program Files\Wolfram Research\Mathematica\11.0\math.exe" -noprompt -script test.m

then I would expect that there is a file "test.log" with the error message "could not open "wrong?file*name.xlsx"" or similar, however, there is only "Done." written out.

What am I doing wrong? What would be good practise to use Mathematica in script mode?

$\endgroup$
0

2 Answers 2

1
$\begingroup$

Two problems:

Use === and =!= to test for the equality of strings. == and != is for mathematical equality and won't evaluate to True or False for symbols:

x != "asd"
(* x != "asd" *)

This is likely causing your code to fail.

When the first argument of If is neither True not False and the fourth argument (look it up!) isn't present, it does not evaluate:

If[1, a]
(* If[1, a] *)

If[1, a, b, c]
(* c *)

If[x == y, foo]
(* If[x == y, foo] *)

Another problem is that you use the head execFailure (a symbol) but then test for "execFailure" (a string). This isn't used in your test script, but be aware of it.

$\endgroup$
0
$\begingroup$

Just for reference, this code does the job (I believe):

execFailureQ[expr_] := MatchQ[expr, _execFailure];

safeExec[expr_, OptionsPattern[]] := Module[{res, err, logF, quitCode},
   res = EvaluationData[Evaluate[expr]];
   If[res["Success"], Return[res["Result"]]];
   err = StringRiffle[ToString /@ res["MessagesText"], ", \n"];
   logF = OptionValue["logFile"];
   If[logF =!= None, WriteString[logF, err <> "\n"]];
   quitCode = OptionValue["quitCode"];
   If[quitCode =!= None, Quit[quitCode]];
   Return[execFailure[err]];
];
SetAttributes[safeExec, HoldFirst];
Options[safeExec] = {"logFile" -> None, "quitCode" -> None};

Thanks for pointing the problems out!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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