您好我只是创建一个java应用程序来外部运行我的python代码。但它想要给我出局。 这是我的java代码: -
package com.epatient;
import java.io.*;
public class InterpreterExample {
//static String workingDir = System.getProperty("user.dir");
//static String appDir = workingDir + "\\epatient\\epatient_prediction.py";
public static void main(String a[]){
try{
String appDir = "C:\\Users\\Thushara Kasun\\Documents\\juno\\serial.port\\epatient\\epatient_prediction.py";
System.out.println(appDir);
ProcessBuilder pb = new ProcessBuilder("python",appDir);
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ret = in.readLine();
System.out.println("value is : "+ret);
}catch(NumberFormatException e){e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
}
这是我的python代码: -
import sys
from sklearn.externals import joblib
import pandas as pd
import numpy as np
import csv
from sklearn.decomposition import PCA
import re
import psycopg2
import datetime
import time
con = None
bio_data = None
heart_rate = None
so2_data = None
temp_data = None
bp_data = None
try:
con = psycopg2.connect(database='Epatient_user_1', user='postgres', password='root')
cur = con.cursor()
...#database access codes omited
model_name = 'trained_model'
est = joblib.load(model_name)
predictions = est.predict(data)
#predictions
# <codecell>
#sys.stdout.write(str(int(predictions[0])))
#sys.stdout.flush()
#print int(predictions[0])
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
#print st
cur.execute('INSERT INTO patient_status (STATUS,TIME,PROCESSED) VALUES (' + str(int(predictions[0])) + ',\''+ st + '\',0);')
con.commit()
except psycopg2.DatabaseError, e:
print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
sys.stdout.write(str(int(predictions[0])))
sys.stdout.flush()
#print int(predictions[0])
Java out put只是值是:null 它运行得很好的python代码没有问题。我只想打印一个字符串格式的布尔值。同时我需要在我的本地postgresql数据库中更新该值(通过python代码,单独工作)。我的java应用程序只是没有执行python代码。请帮助我,或者给我另一种方法来解决这个问题。
答案 0 :(得分:1)
我认为您的Java代码没问题,然后尝试更改您的Python脚本。
拜托,你愿意改变print int(predictions[0])
行:
sys.stdout.write(str(predictions[0]))
sys.stdout.flush()
sys.stdout
会将数据打印到控制台输出流
仅用于测试,将脚本的绝对路径放在ProcessBuilder构造函数中:
String appDir = "C:\\my\\full\\path\\to\\script.py";
ProcessBuilder pb =
new ProcessBuilder("python", appDir);
Process p = pb.start();
....