Haariys
Haariys

Reputation: 41

Passing variables to a python script from java

ok so here is the question already asked but the answers dont seem to help much. I am able to run python script using jython and the answer posted in that question but i am not able to pass variables ... when i run the program the error says that no such variable as arg1 arg2 and arg3 ... what am i doing wrong?

String[] arguments = {"myscript.py", "arg1", "arg2", "arg3"};
PythonInterpreter.initialize(System.getProperties(), System.getProperties(),arguments);
org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();
StringWriter out = new StringWriter();
python.setOut(out);
python.execfile("myscript.py");
String outputStr = out.toString();
System.out.println(outputStr);

and here is the python script

def myFunction(arg1,arg2,arg3):
    print "calling python function with paramters:"
    print arg1
    print arg2
    print arg3
myFunction(arg1,arg2,arg3)

now error says arg1 arg2 and arg3 not declared

Upvotes: 3

Views: 2976

Answers (1)

Zefick
Zefick

Reputation: 2119

You should access the command line arguments via sys.argv variable as described here: https://www.tutorialspoint.com/python/python_command_line_arguments.htm

So the right code:

myFunction(sys.argv[0], sys.argv[1], sys.argv[2])

Upvotes: 2

Related Questions