有 Java 编程相关的问题?

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

我无法从java运行python脚本,我认为这是因为该脚本没有执行权限

每当按下gui(swing)上的按钮时,我都会尝试运行python脚本。但是,脚本从未运行,我不知道如何修复此问题。我知道脚本可以独立工作,它应该是py而不是python,因为windows和我的文件系统是ntfs

到目前为止,我一直在尝试使用以下代码:

myBtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          Process p = Runtime.getRuntime().exec("py myScript.py");

        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
});

我不认为我可以chmodntfs之类的东西,但我尝试通过右键单击python文件来设置权限,并试图破坏安全设置。对用户脚本的完全控制不起任何作用

python脚本具有以下权限,我猜我的代码不工作,因为它没有执行权限

-rw-r--r--

共 (1) 个答案

  1. # 1 楼答案

    使用完整的python可执行路径,而不是“py”。它以只读权限执行文件

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Scanner;
    
    public class Sample {
    
        public static void main(String[] args) throws Exception {
            try {
                Process p = Runtime.getRuntime().exec("C:/Windows/py myScript.py");
                String cmdOutput = null;
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                // read the output from the command
                while ((cmdOutput = stdInput.readLine()) != null) {
                    System.out.println(cmdOutput);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
    

    我的脚本。py

    print("This line will be printed.")
    

    输出:

    C:\Users\Administrator\Documents\demo>javac Sample.java
    
    C:\Users\Administrator\Documents\demo>java Sample
    This line will be printed.