Login  Register

Re: calling python script from macro

Posted by Pariksheet Nanda on Nov 15, 2015; 10:09pm
URL: http://imagej.273.s1.nabble.com/calling-python-script-from-macro-tp5014952p5014953.html

Hi Aryeh,

On Sun, Nov 15, 2015 at 2:40 PM, Aryeh Weiss <[hidden email]> wrote:
>
> Is there a way to run a python script form a macro?
> i tried
> call(ij.plugin.Macro_Runner.runPython(pathToPythonScript, "");
> but that did not work.

There were 2 things that needed to be changed:

    jythonText = File.openAsString(pathToPythonScript);
    call("ij.plugin.Macro_Runner.runPython", jythonText, "");

... namely:
1) One needs to put quotes around the first class.method parameter to
call(...) as described in the function reference
(http://imagej.nih.gov/ij/developer/macro/functions.html#C).
2) Instead of passing the path to the Jython file, one must instead
read in the file text for runPython(...) to interpret.


On the other hand if you are not trying to run an ImageJ Jython script
(e.g. using ImageJ specific imports, etc) and are instead running a
CPython script (https://learnwithtina.wordpress.com/2014/07/20/what-is-the-difference-between-python-and-cpython/)
in a "traditional" Python interpreter outside of ImageJ in a separate
process one would use exec(...):

    exec("python", pathToPythonScript).

Note with exec(...) one must use commas to separate any part of the
command that requires spaces.  For example while one may normally run
"python -c print(123)" on the command-line, in exec it is:

    output = exec("python", "-c", "print(123)");
    print(output);

Also note that "output" only seems to contain stdout not stderr *.
See the exec(...) examples here:
http://imagej.nih.gov/ij/macros/ExecExamples.txt


> --aryeh

Pariksheet


* Maybe to also see stderr one should use e.g. 2>&1 redirection, but
my weird system hangs on exec("sh", "-c", "ls") alone although
exec("ls") works fine.  A mystery for another time.

--
ImageJ mailing list: http://imagej.nih.gov/ij/list.html