我正在 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/