java调⽤python代码接⼝_java直接调⽤python脚本,并传递参
数代码实例
最近陆续⽤python写了很多⽂件处理脚本,虽然功能都⽐较简单 ,但还是感觉到python对⽂件处理的简洁⾼效 ,越发觉得java的语法相当的繁琐~
接到个需求处理ftp数据接⼝ 。所以想把python脚本也⽤上。java代码定时扫描ftp数据仓库 ,调⽤python脚本⼊库。
直接采⽤java执⾏系统命令的⽅式
@Async
public void readFileByPython(List filePaths) throws FileNotFoundException {
URL localSrcUrl = Resource("");
String localSrcPath = Path();
localSrcPath = localSrcPath.substring(1, localSrcPath.length());
String pythonFile = localSrcPath + "PythonFileHandle.py";
int size = filePaths.size() + 2;
String[] args = new String[size];
args[0] = "python";
args[1] = pythonFile;
for(int i =0;i
int index = i+2;
args[index] = (i);
}
try {
System.out.println("start");
Process proc = Runtime().exec(args);
InputStream is = ErrorStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("");
while((line = br.readLine())!=null){
System.out.println(line);
System.out.println("");
int exitValue = proc.waitFor();
System.out.println("Process exitValue="+exitValue);
}
System.out.println("end");
} catch (Exception e){
e.printStackTrace();
}
}
python转java代码String[] args = new String[size];
args[0] = "python";  args[1] = pythonFile;    args[0]表⽰要执⾏的是python 脚本 ,args[1] 脚本⽂件的全路径
该⽅法调⽤ AbstractReadFileLine.class ⽂件路径下的 PythonFileHandle.py 脚本 ,并传⼊String数组类型的参数(需要处理的⽂件全路径)
PythonFileHandle脚本接受java传⼊的⽂件路径参数(数组),解析并⼊库
PythonFileHandle.py 代码
import pymssql,time,sys
reload(sys)
sys.setdefaultencoding("utf-8")
class MSSQL:
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def __GetConnect(self):
if not self.db:
raise(NameError,"")
< = t(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
cur = ursor()
if not cur:
raise(NameError,"")
else:
return cur
def ExecQuery(self,sql):
cur = self.__GetConnect()
resList = cur.fetchall()
#
return resList
def ExecNonQuery(self,sql):
cur = self.__GetConnect()
def insertToCloseList(data ,ms):
sql = "insert into t_isee_closelist_infos
(WORK_ORDER_ID,CRM_Cdsc_Id,APPRAISE_TYPE,CRM_Accept_Date,latn_code,theme_row_id,TASK_EXECUTE_ROW_ID,CRM_Acce values ( '"
temp ="' , '"
sqlStr = temp.join(data)
sql = sql + sqlStr + "')"
ms.ExecNonQuery(sql)
ms = MSSQL(host="172.30.0.186",user="sa",pwd="",db="test")
fengefu = '$%$'
for i in range(1, len(sys.argv)):
read = open(sys.argv[i] ,'r')
for line in read:
line=line.strip('\n')
data = line.split(fengefu)
insertToCloseList(data,ms)
read.close
sys.argv[0] 存储的是py⽂件⾃⾝的路径,故接受参数从sys.argv[1]开始。
以上所述是⼩编给⼤家介绍的java调⽤python脚本传递参数详解整合,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及
时回复⼤家的。在此也⾮常感谢⼤家对脚本之家⽹站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。