我需要在我的Java应用程序中运行一个Python脚本(写入输入和读取输出),最终将上传到Web上。我如何做到这一点,使其与网络兼容?我在Java中尝试了Jython
和Runtime.exec()
之类的东西,我认为两者都需要在计算机上安装Python
(如果我错了,请纠正我)但我希望应用程序能够由网络上的任何人管理。
Python脚本导入win32com.client
以对COM
对象进行操作。它读入.csv文件,运行外部软件,然后使用RCSV(...),Run(...)和WCSV(...)方法写入.csv文件。我希望直接从我的Java应用程序访问这些数据,而不是.csv文件。这是我的python脚本完整的参考:
import win32com.client
from win32com.client import VARIANT
import csv
# This will import VT_VARIANT
import pythoncom
#dictionary function designed to read .csv file
def RCSV(address):
input=[]
csv_reader = csv.DictReader(open(address, 'r'), delimiter=',', quotechar='"')
headers = csv_reader.fieldnames
for line in csv_reader:
for i in range(len(csv_reader.fieldnames)):
input.append(line[csv_reader.fieldnames[i]])
InVal=[]
for i in range(int(len(input)/len(headers))):
InVal.append([])
for i in range(len(InVal)):
for j in range(i*len(headers), (i+1)*len(headers)):
InVal[i].append(input[j])
return InVal
#dictionary function which writes a .csv file given its address
def WCSV(address, output, headers):
with open(address, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=headers, lineterminator = '\n')
writer.writeheader()
for i in range(len(output[0])):
writer.writerow({headers[x]: output[x][i] for x in range(len(headers))})
def Run(InType,InDesc,InVal,OutType,OutDesc):
FieldArray = VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_ARRAY, InDesc)
AllValueArray=[None]*len(InVal)
for i in range(len(InVal)):
AllValueArray[i]=VARIANT(pythoncom.VT_VARIANT | pythoncom.VT_ARRAY, InVal[i])
object.ChangeParametersMultipleElement(InType, FieldArray, AllValueArray)
object.RunScriptCommand("SolvePowerFlow")
OutVal = object.GetParametersMultipleElement(OutType, OutDesc,'')
return OutVal
# This will establish the connection
object = win32com.client.Dispatch("pwrworld.SimulatorAuto")
filename= r"C:\Users\janusz\Desktop\NTU microgrid topology\ICESO Scaledown microgrid.pwb"
object.OpenCase(filename)
# Reading inputs from a .csv
ADIN='IN.csv'
InVal = RCSV(ADIN)
InType = "GEN"
InDesc = ["BusNum", "GenID", "GenMW"]
OutType = "BUS"
OutDesc = ["BUSNUM", "BUSNAME", "BUSPUVOLT", "BUSANGLE", "BUSKVVOLT"]
OutVal = Run(InType,InDesc,InVal,OutType,OutDesc)
ADOUT='OUT.csv'
WCSV(ADOUT,OutVal[1],OutDesc)
#This will close the connection
del object
object = None
答案 0 :(得分:2)
Jython在没有安装Python的情况下工作,因为它是Python的100%Java实现。话虽这么说,只有win32
个客户端可以运行win32 COM。所以,除了win32之外,它永远不会在任何平台上兼容(并且可能通过哇赢得64)。