【问题标题】:How to execute if statement using Jython如何使用 Jython 执行 if 语句
【发布时间】:2015-02-02 02:31:29
【问题描述】:
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!'");
}
}

我需要能够从 Java 程序执行 Python 代码,因此决定尝试 Jython,但我不熟悉它。我尝试执行上面的代码,但得到了错误:“线程中的异常“main”SyntaxError:(“mismatched input '' Expecting INDENT”, ('', 1, 9, 'if 2 > 1:\n')) ”。任何想法这意味着什么或我如何使用 PythonInterpreter 执行 if 语句?

【问题讨论】:

  • 你在使用 Eclipse 吗?
  • 是的,我正在使用 Eclipse!
  • 我有一个建议,请稍等,我会发布另一个答案。

标签: java python jython


【解决方案1】:

条件必须作为单个字符串输入,并且您有一个额外的括号:

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

【讨论】:

  • 非常感谢,太完美了!
【解决方案2】:

您可以调用解释器来运行文件,而不是使用字符串逐行执行脚本。您所要做的就是为您的 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");
    }
}

【讨论】:

  • 为什么要添加新答案而不是将其编辑到现有答案中?
  • 因为它们是两个不同的想法。为什么你认为堆栈交换会添加这样的功能?
  • 如果我这样做,我是否能够在程序运行时输入程序,例如对于像这样的 python 程序:name=raw_input() print('Hi '+name) 如果是这样,如何?
  • 刚刚尝试了以下代码:link 并得到了错误:线程“main”中的异常 SyntaxError: ("no possible alternative at input '='", ('test1.py', 1 , 10, 'print(name=raw_input()\n'))"。
  • 那甚至不是正确的python。您在打印语句中有两个语句。
猜你喜欢
  • 2010-09-21
  • 2020-04-14
  • 1970-01-01
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多