我无法从 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();

        }

      }

});

我不认为我可以 chmod ntfs 的东西,但我尝试通过右键单击 python 文件来设置权限并试图弄乱安全设置。用户对脚本的完全控制什么都不做。


python 脚本具有以下权限,我的猜测是我的代码不起作用,因为它没有执行权限。


-rw-r--r--


慕少森
浏览 314回答 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();        }    }}myScript.pyprint("This line will be printed.")输出:C:\Users\Administrator\Documents\demo>javac Sample.javaC:\Users\Administrator\Documents\demo>java SampleThis line will be printed.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python