jython實現java運行python代碼


Jython是一種完整的語言,而不是一個Java翻譯器或僅僅是一個Python編譯器,它是一個Python語言在Java中的完全實現。最近的一個項目需要將python代碼轉換成java實現,所以用了一下jython。

試用了jython的2.7的版本發現運行一直出錯,不知道是不是版本的原因,但是2.5的版本還是可以的。

第一步,先來一個簡單的(先確定你已經下載添加了對應的jar包)

java代碼:

PythonInterpreter interpreter = new PythonInterpreter(); 
interpreter.execfile(
"/home/桌面/PycharmProjects/first/1.py");

python代碼:

print("hello jython")

輸出:

第二步:調用方法(不含參數)

java代碼:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("/home/ybf/PycharmProjects/first/1.py");
PyFunction func_first = (PyFunction)interpreter.get("first",PyFunction.class);
PyFunction func_second= (PyFunction)interpreter.get("second",PyFunction.class);
PyObject pyobj = func_second.__call__();
System.out.println(pyobj);

python代碼:

def first():
print("first ...........")

first()

def second():
a=100
b=50
return a+b

輸出:

第三步:調用方法(含參數)

java代碼:

PythonInterpreter interpreter = new PythonInterpreter(); 
interpreter.execfile("/home/ybf/PycharmProjects/first/1.py"); 

PyFunction func_third= (PyFunction)interpreter.get("third",PyFunction.class); 

PyObject pyobj = func_third.__call__(new PyInteger(4), new PyInteger(2));
System.out.println(pyobj);

python代碼:

def third(a,b):
c=sub(a,b)
d=sub(b,a)
return c*d

def sub(a,b):
return a-b

輸出:

第四步:關於中文處理,這是一個很麻煩的方面,大家可以看下面的例子

java代碼:

String a = "你好"; PyFunction func= (PyFunction)interpreter.get("word_process",PyFunction.class); PyObject pyobj = func.__call__(new PyString(a)); System.out.println(pyobj.toString());

python代碼:

def word_process(a): if a=="你好": print(True) else: print(False) print(a) return a 

結果:

這里可以看到在Python里面輸出在eclipse輸出的是?,其實輸出的是“你好”,但是因為平台的原因所以顯示?(個人的理解),而且大家可以發現在python中的“你好”不等於java里面的“你好”,這方面本人還不知道,不知道有沒有大佬知道,怎樣處理才返回True,

str(a).encode('utf-8')=="你好".encode("utf-8")這樣返回的也是False

第五步:打開txt文本

這里注意python里面的代碼,如下:

 

f=open('src/dic/v.txt','rt')#注意文件路徑 while(True): line=f.readline() if not line: break
    print(line)

 

如果這里使用 with open('src/dic/v.txt','rt') as f 但在eclipse報錯如下:

 

 今天寫到這里,有時間再更新 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM