问题
I want to invoke Jython scripts from command line, p.e.
$ /Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --headless little_jython_script.py
I know about Python's (and therefore Jython's) capability to take parameters by
import sys
params = sys.argv[1:]
and then calling the script with something like
$ /Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --headless jython_script_with_params.py param1 param2 param3
.
However, according to to the ImageJ webpage http://imagej.net/Script_parameters it is also possible to code the use of parameters in Jython similar to the Greeting.py example from that website
# @String name
# A Jython script with parameters.
# It is the duty of the scripting framework to harvest
# the 'name' parameter from the user, and then display
# the 'greeting' output parameter, based on its type.
print "Hello, " + name + "!"
The questions is: How do I specify the parameter name
in a command line call $/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --headless Helloworld.py
?
回答1:
The way parameters are available depends on the calling command, where the difference is the additional flags --ij2
and --run
in the Jython way. Either sys.argv
or # @String
etc. work, but not both at the same time
1. The classical Python way with sys.argv
$/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --headless JythonScript.py param1 param2
harvests the parameters for JythonScript.py
in the classical python way with sys.argv
, i.e.
# @String param1 ### Does NOT work
import sys
program_name = sys.argv[0]
paramvalue1 = sys.argv[1]
paramvalue2 = sys.argv[2]
2. The Jython specific way with # @String etc.
$/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --ij2 --headless --run JythonScript_2.py 'param1=value, param2=value'
takes parameters in the Jython way
# @String param1
# @Long param2
### See http://imagej.net/Script_parameters#Parameter_types
### for a complete list of parameter types
import sys
check = sys.argv
#here check is a length 1 list containing en empty string: check ==['']
Note the quotes around the two comma-separated param=value
pairs. Both single and double quotes work. They can be omitted when only 1 parameter is present. For string parameters make sure to enclose them into the other kind of quotes, or omit the quotes when the string is purely alphanumeric like
$/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx --ij2 --headless --run JythonScript_3.py 'stringparam1="string with ',' and space ", stringparam2=abc123'
来源:https://stackoverflow.com/questions/41189104/running-jython-script-from-terminal-with-parameter