简体   繁体   English

如何使用Jython执行if语句

[英]How to execute if statement using Jython

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. 我需要能够从Java程序执行Python代码,因此决定尝试Jython,但我不熟悉它。 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'))". 我尝试执行上面的代码,但收到错误:“线程“ main”中的异常” SyntaxError :(“输入不匹配”,预计为INDENT”,(“ 1、9,'if 2> 1:\\ n')) ”。 Any ideas what this means or how I can otherwise execute an if statement using the PythonInterpreter? 有什么想法意味着什么,或者如何使用PythonInterpreter执行if语句?

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!'");
    }
}

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. 您所要做的就是提供python文件的文件路径,在此示例中,将script.py放置在src文件夹中。

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM