有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用绝对路径从Java运行Python文件?

我想运行一个名为foo的python脚本。我有绝对路径,比如说: /用户/me/pythonscripts/

我试过跑步:

String cmd="/Users/me/pythonscripts/"
String py="foo"
Runtime.getRuntime().exec("cd "+cmd);
Runtime.getRuntime().exec("python "+py+".py");

但它确实运行python文件


共 (2) 个答案

  1. # 1 楼答案

    尝试使用更像

    Runtime.getRuntime().exec("python "+cmd + py + ".py");
    

    相反。每个exec都是它自己的进程,多个exec彼此没有关系

    您也应该考虑使用^ {CD3>},因为这为您提供了一个很好的可配置级别,例如,您可以更改执行路径上下文…

    ProcessBuilder pb = new ProcessBuilder("python", py + ".py");
    pb.directory(new File(cmd));
    pb.redirectError();
    //...
    Process p = pb.start();
    

    另外,请注意,Python的输出流存在问题,这可能会阻止Java在完全完成之前读取它,如果

    有关更多详细信息,请查看Java: is there a way to run a system command and print the output during execution?

    另外,确保python在shell的搜索路径内,否则还需要指定命令的完整路径

  2. # 2 楼答案

    这是我的工作

        public static void main(String[] args)  throws IOException{
    
        Runtime runtime = Runtime.getRuntime();
        Process p1 = runtime.exec("D:\\programs\\Anaconda3\\Scripts\\spyder.exe \"C:\\Users\\Al-Hanouf\\codes\\PageRank.py\"");
        System.out.print("is process alive = "+p1.isAlive());
    
    }