使用ProcessBuilder调用python脚本以在XLSX工作本中创建图形



下面是我的java代码,我正试图从java调用一个python脚本。python脚本作业是在xlsx工作表中创建一个图形。当我自己运行python脚本时,它运行得很好,但当我从java调用它时,什么都不会发生,也没有错误。

公共类CallPython{

private String pythonScriptPath;

CallPython(){

}

public void executePythonScript() throws Throwable {

try {
String pathScript = System.getProperty("user.dir")+"\pythonScripts\script.py";
//String venvPath = System.getProperty("user.dir")+"\pythonScripts\venv\Scripts\activate";
ArrayList<String> listCommand = new ArrayList<>();
listCommand.add("python");
listCommand.add(pathScript);
System.out.println("the path : " +pathScript);
//System.out.println("the venv path : " +venvPath);
ProcessBuilder builder = new ProcessBuilder(listCommand);
builder.redirectErrorStream();
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader readerError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String lines = null;

while((lines=reader.readLine())!=null) {
System.out.println("lines "+lines);
}
while ((lines= readerError.readLine()) != null) {
System.out.println(lines);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}

}


public static void main(String[]args(throws Throwable{

CallPython newcall = new CallPython();
newcall.executePythonScript();

}

}

进口熊猫作为pd

def create_pivot((:#创建图表对象。

# Some sample data to plot.
list_data = [10, 20, 30, 20, 15, 30, 45]
# Create a Pandas dataframe from the data.
df = pd.DataFrame(list_data)
# Create a Pandas Excel writer using XlsxWriter as the engine.
excel_file = 'book.xlsx'
sheet_name = 'Sheet1'
writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name)
# Access the XlsxWriter workbook and worksheet objects from the dataframe.
# This is equivalent to the following using XlsxWriter on its own:
#
#    workbook = xlsxwriter.Workbook('filename.xlsx')
#    worksheet = workbook.add_worksheet()
workbook = writer.book
worksheet = writer.sheets[sheet_name]
# Create a chart object.
chart = workbook.add_chart({'type': 'column'})
# Configure the series of the chart from the dataframe data.
chart.add_series({
'values': '=Sheet1!$B$2:$B$8',
'gap': 2,
})
# You can also use array notation to define the chart values.
#    chart.add_series({
#        'values':     ['Sheet1', 1, 1, 7, 1],
#        'gap':        2,
#    })
# Configure the chart axes.
chart.set_y_axis({'major_gridlines': {'visible': False}})
# Turn off chart legend. It is on by default in Excel.
chart.set_legend({'position': 'none'})
# Insert the chart into the worksheet.
worksheet.insert_chart('D2', chart)
print("workbook path: ",workbook)
# Close the Pandas Excel writer and output the Excel file.
writer.save()

如果name==">main":create_pivot((

您的进程可能正在冻结,因为您没有正确(同时(使用stdout+stderr流,因此如果stderr缓冲区超过默认大小,则应用程序将无法继续,并且将显示为冻结。您可以通过将stderr合并到stdout并只读取一个流而不是两个来检查这一点:

ProcessBuilder pb = new ProcessBuilder(listCommand);
pb.redirectErrorStream(true);
Process process = pb.start();
process.getInputStream().transferTo(System.out);
int rc = process.waitFor();
if (rc != 0)
throw new RuntimeException("Command: "+pathScript+" failed rc=" + rc);

请注意,在您的代码示例中,不带参数的调用pb.redirectErrorStream()不起任何作用。

最新更新