0

All I'm trying to do is pass an argument to the python interpreter so it can be passed as an argument for a module.

E.g. I have the following defined in a py file:

    def print_twice(test):
       print test
       print test

I want to pass it the argument "Adam", so I've tried:

    // Create an instance of the PythonInterpreter
    PythonInterpreter interp = new PythonInterpreter();

    // The exec() method executes strings of code
    interp.exec("import sys");
    interp.exec("print sys");

    PyCode pyTest = interp.compile("Adam", "C:/Users/Adam/workspace/JythonTest/printTwice.py");
    System.out.println(pyTest.toString());

I've also tried:

        interp.eval("print_twice('Adam')");

I've been using the following Jython API but I don't understand it well: http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#compile%28java.lang.String,%20java.lang.String%29

I would be very grateful for your advices.

Thank you

2 Answers 2

1

This should work:

interp.exec("import YOUR_PYTHON_FILE.py");
interp.exec("YOUR_PYTHON_FILE.print_twice('Adam')");

Its equivalent in a python console is this:

>>> import YOUR_PYTHON_FILE.py
>>> YOUR_PYTHON_FILE.print_twice('Adam')
Adam
Adam
Sign up to request clarification or add additional context in comments.

13 Comments

Thanks for your response. I got the following error in the console: Exception in thread "main" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named printTwice.
printTwice.py is saved in the same project. I've also tried moving it to the source folder. I'm going wrong somehwere, but not sure where...
When executing in the console printTwice.py has to be in the working directory (where you are when you execute the console) if you follow my code. The path using Jython should be specified in the Jython Documentation: jython.org
I'm not sure how to save the py file to the same working directory, so I will try to find out how to do this.
Thanks Andreu..... I've opened a new one here - stackoverflow.com/questions/31756461/….
|
0

You shouldn't need to explicitly compile the script, just import it and the interpreter will take care of compilation. Something like this (assuming printTwice.py is in the working directory of your program:

interp.exec("from printTwice import print_twice");
interp.exec("print_twice('Adam')");

You don't need to use interp.eval on the second line assuming that print_twice does actually contain print statements; if it just returns a string then you probably want
System.out.println(interp.eval("print_twice('Adam')"));.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.