![](/img/trans.png)
[英]How to get java getRuntime().exec() to run a command-line program with arguments?
[英]How to Run a Python Program that Takes Command-Line arguments from within a Java Program
我知道要從Java程序中運行另一個Java程序,你可以使用如下代碼:
Runtime.getRuntime().exec("/**A command goes here*/")
但是,我如何運行一個采用命令行參數的Python程序? 更具體地說,我的Java程序將文件作為命令行參數。 然后我將此文件傳遞給Python程序,然后在同一目錄中生成另一個文件。 我將能夠訪問這個新文件。
我可以簡單地打電話:
Runtime.getRuntime().exec("python /**directory_of_the_python_program arguments_for_program*/");
我對“exec(...)”里面的內容也有點困惑。
嘗試捕獲標准輸出,因此您可以使用python中的print
輸出到此流:
try {
Process p = Runtime.getRuntime().exec("python yourProgram.py thearg1 thearg2");
p.waitFor();
InputStream stderr = proc.getOutputStream();
InputStreamReader in = new InputStreamReader(stdout);
BufferedReader reader = new BufferedReader(in);
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("Python says: " + line);
}
int exitVal = proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
在你的python程序中,輸出到Java程序,使用print如:
print 'Hi!'
要查看Java程序發送給您的內容,可以使用sys.argv
:
print 'The Java program sent me: ', str(sys.argv)
注意:我不是python專家,並沒有做太多。 如果我的語法錯誤,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.