0
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
    PythonInterpreter interp = new PythonInterpreter();
    interp.exec("if 2 > 1:");
    interp.exec("   print('in if statement!'");
}
}

I need to be able to execute Python code from a Java program, so decided to try out Jython, but I'm unfamiliar with it. I tried executing the above code, but got the error: "Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))". Any ideas what this means or how I can otherwise execute an if statement using the PythonInterpreter?

3
  • Are you using Eclipse? Commented Feb 1, 2015 at 17:01
  • Yep I am using Eclipse! Commented Feb 1, 2015 at 17:25
  • I have a suggestion for you just hold on a second while I post another answer. Commented Feb 1, 2015 at 17:26

2 Answers 2

1

Conditionals must be entered as a single string and you have an extra parenthesis:

import org.python.util.PythonInterpreter;

public class JythonTest {
    public static void main(String[] args) {
        PythonInterpreter interp = new PythonInterpreter();
        interp.exec("if 2 > 1: print 'in if statement!'");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Rather than executing a script line by line with strings you can invoke the interpreter to run a file. All you have to do is provide a file path to your python file, in this example place script.py in the src folder.

script.py

if 2 > 1:
    print 'in if statement'

JythonTest.java

import org.python.util.PythonInterpreter;

public class JythonTest {
    public static void main(String[] args) {
        PythonInterpreter interp = new PythonInterpreter();
        interp.execfile("src/script.py");
    }
}

12 Comments

Why would you add a new answer instead of editing it into your existing one?
Because they're two separate ideas. Why do you think stack exchange would add such a feature?
If I do this, will I be able to input to the program whilst it is running e.g for a python program like this: name=raw_input() print('Hi '+name) If so, how?
Just tried the following code: link And got the error: Exception in thread "main" SyntaxError: ("no viable alternative at input '='", ('test1.py', 1, 10, 'print(name=raw_input()\n'))".
That's not even proper python. You have two statement in a print statement.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.