0
$\begingroup$

Is there a way to tell Export to hold its arguments and just Export.

I tried to use SetAttributes[Export,HoldRest];Attributes[Export] and HoldRest now appears as one of its attributes but running the following still returns error since it is not stopping the evaluation of its arguments.

file=FileNameJoin[{NotebookDirectory[],"squares.m"}];
Export[file,If[Length[$ScriptCommandLine]==1,
    Print["No expressions were given to square."],

    args = Rest[$ScriptCommandLine];
	squares = Quiet @ Map[Replace[ToExpression[#], {$Failed:>ToString[#,InputForm]^2, x_ :> x^2}]&, args];
    MapThread[Print["The square of ", #1, " is ", #2, "."]&, {args, squares}]
],"Text"];
$\endgroup$
  • 1
    $\begingroup$ Why would you do all that within Export? Take the If outside of Export (e.g. If[yourCondition, Export[file, yourstuff], elseStuff]), and only apply Export when it is appropriate to do so. $\endgroup$ – MarcoB Apr 22 '19 at 0:31
  • $\begingroup$ Why don't you use WriteString? Alternatively, you can use Export["file",Unevaluated[ exp ]]; $\endgroup$ – Wen Chern Apr 22 '19 at 1:17
1
$\begingroup$

I think trying to write the code so that everything is done in one Export expression is going about it wrong. I simply don't see any advance to it.

Here a script that I wrote that I believe does what you are trying to accomplish with simple, straightforward code. Besides working, it has the advantage of being easy to understand and debug.


#!/Applications/Mathematica.11.3.0.app/Contents/MacOS/wolframscript

argv = Rest @ $ScriptCommandLine;
argc = Length @ argv;
If[argc == 0, Print["No expressions were given to square."]; Exit[]];

file = FileNameJoin[{$HomeDirectory, "Desktop", "squares.txt"}];

Module[{vals, sqs, recds},
  vals = Select[(ToExpression /@ argv), NumberQ];
  sqs = vals^2;
  recds =
    MapThread[
      ToString[StringForm["The square of `1` is `2`.", #1, #2]] &, {vals, sqs}];
  Export[file, recds];
  Exit[]]

A Terminal session to test this script went as follows:

session


The file produced by the 1st execution of squares looked like this:

file

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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