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

我需要能夠從Java程序執行Python代碼,因此決定嘗試Jython,但我不熟悉它。 我嘗試執行上面的代碼,但收到錯誤:“線程“ main”中的異常” SyntaxError :(“輸入不匹配”,預計為INDENT”,(“ 1、9,'if 2> 1:\\ n')) ”。 有什么想法意味着什么,或者如何使用PythonInterpreter執行if語句?

必須將條件詞作為單個字符串輸入,並且您需要附加括號:

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

您可以調用解釋器來運行文件,而不是通過字符串逐行執行腳本。 您所要做的就是提供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