Jython equivalent to IJ Macro exec?

I have a CPython script that I have previously used ImageJ macro language to call from the command prompt (https://imagej.nih.gov/ij/macros/ExecExamples.txt). Is there a Jython equivalent of the exec command to call a CPython script from command prompt?

The closest I’ve found seems to be subprocess (https://www.jython.org/jython-old-sites/docs/library/subprocess.html) but I can’t seem to import this.

Thanks :smile:

Maybe you can try using the java equivalent from jython, something like that

from java.lang import Runtime
run = Runtime.getRuntime()
proc = run.exec("YourCommand")

Let me know if this works for you, I think I tried once something similar but without much success…


Thanks @LThomas, this worked for me.

Here’s an example Jython script, and Python script to run (cmd_test.txt - it’s a Python script but I can’t upload .py files)

cmd_test.txt (178 Bytes)

from java.lang import Runtime
from java.io import BufferedReader, InputStreamReader

# Set up parameters for python script to run here
path = "C:/Users/"
script = "cmd_test.txt"
cmd_str = "cmd /k cd {} & python {} & exit()".format(path, script)

# Start a new process, run python script from cmd
run = Runtime.getRuntime()
proc = run.exec(cmd_str)

# Collect output from stdout and stderr, print to console
stdout_reader = BufferedReader(InputStreamReader(proc.getInputStream()))
stderr_reader = BufferedReader(InputStreamReader(proc.getErrorStream()))

def print_output(output_reader):
	Prints output of stdout or stderr to console

	output_reader : BufferedReader object
		Reads either stdout or stderr
		List of all lines in output_reader as str
	output_list = []
	output_single = output_reader.readLine()
	while output_single != None: # while line in output_reader is not empty
		output_list.append(output_single) # append this line
		output_single = output_reader.readLine() # advance to next line of output_reader

	# print to console
	for line in output_list:

	return output_list

print("stdout: \n")
stdout = print_output(stdout_reader)

print("stderr: \n")
stderr = print_output(stderr_reader)

1 Like

Cool well done! And thanks for the feedback, this will surely be useful to others !