java - 在 Java 中将参数传递给 Python 脚本

标签 java python jython

我正在 java 类中运行 python 脚本,如下所示:

PythonInterpreter interp = new PythonInterpreter();
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
interp.execfile("C:\\Users\\user1\\workspace\\Projectx\\script.py");

问题是 script.py 通常采用这样的命令行参数:

python script.py -i C:/diretory/path -o C:/directory/path

是否可以通过 Java 中的 PythonIntepereter 传递这些参数?

更新:

感谢 Juned Ahsan,我的代码现在如下所示:

String[] args = {"-i " + lawlinkerIfolder.toString() + " -o " + lawlinkerOfolder.toString()};
PythonInterpreter interp = new PythonInterpreter();
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), args);
interp.execfile("C:\\Users\\user1\\workspace\\Projectx\\script.py");

但是脚本仍然没有收到任何参数。

我使用得正确吗?

最佳答案

下面调用中的最后一个参数用于命令行参数:

PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);

来自PythronInterpreter javadocs :

initialize

public static void initialize(Properties preProperties, Properties postProperties, String[] argv)

Initializes the Jython runtime. This should only be called once, before any other Python objects (including PythonInterpreter) are created. Parameters: preProperties - A set of properties. Typically System.getProperties() is used. preProperties override properties from the registry file. postProperties - Another set of properties. Values like python.home, python.path and all other values from the registry files can be added to this property set. postProperties override system properties and registry properties. argv - Command line arguments, assigned to sys.argv.

关于java - 在 Java 中将参数传递给 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17466628/

相关文章:

java - 导入android.support.v4.app.ActivityCompat;

java - 将大字节数组通过管道传输到 Android 应用程序中的 Process

java - Spring WebFlux + Security - 我们有 "remember-me"功能吗?

python - 来自不同文件夹的笛卡尔文件列表

python - 我可以创建一个脚本来测试是否可以在 python 中远程在服务器上使用 SSH 和 PING 命令吗?

java - 查找使用 RSA 生成的数字(这是两个 key 的一部分)的主要因素

python - 使用python将messagePack解析为Json

java - 当仅编码一个参数时,Jython java 调用会抛出异常,要求提供 2 个参数

java - 对于这个小任务,我应该使用 Jython、JRuby、Beanshell、Groovy、Rhino 还是什么?

java - 有没有办法检查文档中是否存在标签名称? (DOM - Jython)