How to execute an array of commands, by storing the commands as strings in the array?

I am trying to apply a series of commands to each slice in an image stack. I was planning to make an array containing the commands as strings and then pass it to a user defined function which apply these commands in order to each slice.
eg: command=newArray(‘setTool(“wand”);’,‘doWand(pos[0], pos[1]);’);

but i am not able to execute these strings. i have tried using doCommand , run() , exec().

any suggestions are welcome, thanks.

Hello Palash -

Here is an IJ Macro (IJM) script that shows how to do this
with eval():

// set up array of commands to run
cmds = newArray (10);
cmds[0] = "print (\"running commands ...\");"
cmds[1] = "newImage (\"sample\", \"RGB noise\", 256, 256, 1);";
cmds[2] = "makeRectangle (40, 40, 50, 50);"
cmds[3] = "setColor (0, 255, 0); fill();"
cmds[4] = "Roi.remove;"
cmds[5] = "print (\"done!\");"

// run the commands using eval()
for (i = 0; i < cmds.length; i++)
	if (cmds[i] != 0)
		eval (cmds[i]);

(You could do more or less the same thing using other scripting
languages, such as jython (python).)

Note the use of “backslash” to escape the “double-quote”
character used to delimit string arguments within command
strings.

However, this seems an odd thing to want to do. Perhaps if
you give us a little more information about your use case
people here could make suggestions about how to accomplish
your goal using more “normal” scripting techniques.

Thanks, mm

1 Like

Hi @Palash_Sarate,

as @mountain_man stated already

If you want make multiple lines of code callable multiple times in a simple way, a function is most likely a good way in doing this via the macro language:

run("Fly Brain (1MB)");
original = getTitle();
run("Split Channels");

selectWindow(original + " (green)");

for (i = 0; i < nSlices; i++) {
	doThisWheneverCalled();
}

function doThisWheneverCalled() {
	doWand(100, 50, 10.0, "Legacy");
	run("Measure");
	run("Next Slice [>]");
}

while actually in that case you could simply add what is in the function directly into the for loop.

run("Fly Brain (1MB)");
original = getTitle();
run("Split Channels");

selectWindow(original + " (green)");

for (i = 0; i < nSlices; i++) {
	doWand(100, 50, 10.0, "Legacy");
	run("Measure");
	run("Next Slice [>]");
}

functions can be a good thing to keep the main macro simpler and make specific blocks of code reusable in different combinations.

1 Like

Hey thanks for your time and effort. Yes I had similar plan too but wanted to do it the way i chose so that it can reused easily somewhere else and easily modified to will (just add commands to an array and call function to apply these command to each slice).

Thanks a lot manjhi the moutain_man, solved! exactly what i needed.