[英]Send commands to Running Python Script
我正在開發一個小型Java應用程序,該應用程序需要啟動python腳本並與其進行交互。 python腳本將在后台運行並等待命令。 在執行每個命令之后,我希望得到一個響應,該響應將轉發回Java應用程序。
我的問題是如何在不重新運行python腳本鈎子的情況下運行命令?
public void startProcess()
{
try {
p = Runtime.getRuntime().exec("python " + scriptPath);
} catch (IOException e) {
e.printStackTrace();
}
}
public String executeCommand(String cmd)
{
String consoleResponse = "";
try {
// how do I perform something similar to p.exec(cmd)
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((consoleResponse += stdInput.readLine()) != null) {
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((consoleResponse = stdError.readLine()) != null) {
}
} catch (IOException e) {
e.printStackTrace();
}
return consoleResponse;
}
編輯:python腳本用於BACpypes。 該腳本執行3件事。 WhoIs:獲取通過bacnet連接的所有設備的列表ReadHexFile:讀取要發送到網絡上所有設備的文本文件。SendFile:將文件發送到所有設備。
我對python沒有經驗,因此將所有這些數據保存在一個腳本中會更簡單。
我想一個選擇是將每個命令分解成自己的腳本,然后將數據傳遞給Java應用程序。
如何在不重新運行python腳本鈎的情況下運行它並運行命令?
您將需要使單個Python腳本繼續監聽新的輸入或請求(來回通信),但是我認為這會有些痛苦,並且會使您的python腳本不如標准input -> process -> output
清晰。 input -> process -> output
流量。
避免運行多個Python腳本的原因是什么?
要將輸入寫入腳本標准輸入,請執行以下操作:
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("python", "path\\to\\script.py");
Process pr = pb.start();
try (BufferedWriter writerToProc = new BufferedWriter(
new OutputStreamWriter(pr.getOutputStream()));
BufferedReader readerOfProc = new BufferedReader(
new InputStreamReader(pr.getInputStream()));
BufferedReader errorsOfProc = new BufferedReader(
new InputStreamReader(pr.getErrorStream()))) {
writerToProc.write("WhoIs\n");
writerToProc.write("ReadHexFile\n"); // is this the syntax?
writerToProc.write("SendFile 'path\to\file.txt'\n");
writerToProc.flush();
StringBuilder procOutput = new StringBuilder();
boolean gaveUp = false;
long waitTime = 10 * 1_000; // 10 seconds
long lastRead = System.currentTimeMillis();
for(;;) {
final long currTime = System.currentTimeMillis();
final int available = readerOfProc.available();
if(available > 0){
// TODO read the available bytes without blocking
byte[] bytes = new byte[available];
readerOfProc.read(bytes);
procOutput.append(new String(bytes));
// maybe check this input for an EOF code
// your python task should write EOF when it has finished
lastRead = currTime;
} else if((currTime - lastRead) > waitTime){
gaveUp = true;
break;
}
}
// readerOfProc.lines().forEach((l) -> System.out.println(l));
// errorsOfProc.lines().forEach((l) -> System.out.println(l));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.