简体   繁体   English

如何在Java中将脚本作为文件运行?

[英]How to run a script as a File in Java?

I have a Python script which is a resource in my project. 我有一个Python脚本,这是我项目中的资源。 Along with the script is an XML file that the script needs in order to run properly. 脚本附带有一个XML文件,该脚本需要该XML文件才能正常运行。 I am reading in both files as an InputStream and then creating temp files for both: 我正在读取两个文件作为InputStream,然后为这两个文件创建临时文件:

InputStream is = (this.getClass().getClassLoader().getResourceAsStream("InterWebApp.py"));
File script = File.createTempFile("script", ".py");
Files.copy(is, script.toPath(), StandardCopyOption.REPLACE_EXISTING);
InputStream is1 = (this.getClass().getClassLoader().getResourceAsStream("setup.xml"));
File xml  = File.createTempFile("config", ".xml");
Files.copy(is1, xml.toPath(), StandardCopyOption.REPLACE_EXISTING);

However, I am not sure how to launch the script as a process: 但是,我不确定如何将脚本作为一个过程启动:

Process p = Runtime.getRuntime().exec("." + script.getAbsolutePath());
p.waitFor();

The above code throws an IOException. 上面的代码抛出IOException。 How do I run script.py and ensure it has access to config.xml ? 如何运行script.py并确保它可以访问config.xml Right now the Python script just parses the XML file using the absolute path, but this path would not be the same for the temp file. 现在,Python脚本仅使用绝对路径来解析XML文件,但是该路径对于临时文件而言将是不同的。

Basically, you're asking yourself for trouble since you ask it for the absolute path, but then prefix it with ".", which is generally a relative path modifier. 基本上,您是在自找麻烦,因为您要求它提供绝对路径,但是要给它加上前缀“。”(通常是相对路径修饰符)。 Try .exec(script.getAbsolutePath()) for starters. 对于初学者,请尝试.exec(script.getAbsolutePath()) Also, depending on your operating system and/or configuration, .py files might or might not be recognized as executable (for example, on Unix systems only files with an executable flag will be recognized as executable). 另外,根据您的操作系统和/或配置, .py文件可能会或可能不会被识别为可执行文件(例如,在Unix系统上,只有带有可执行文件标志的文件才会被识别为可执行文件)。 You might actually want to find the location of the Python executable and pass the script as a parameter. 您实际上可能想要查找Python可执行文件的位置,并将脚本作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM