我有一个python scriptA,它调用另一个python scriptB的函数b。我可以在scriptA中导入scriptB,然后在python中使用scriptB.b调用该函数。
但是我想使用process builder和scriptA从java执行函数scriptB.b.我将scriptB路径作为参数传递,但无法加载模块。
我的Java代码
String pbCommand[] = { python3Path,"scriptAPath/scriptA.py","--scriptB","scriptBPath/scriptB.py"};
ProcessBuilder pb = new ProcessBuilder(pbCommand);
Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
System.out.println("Python Output: " + line);
}
Python ScriptA
def get_opts():
parser = OptionParser()
parser.add_option("-s", "--scriptB", dest="s",help="the second python script to be used")
(options, args) = parser.parse_args()
return (options, args)
def run():
(options, args) = get_opts()
print "test1"
scriptB_path=options.s
scriptb_module = imp.load_source('scriptB', scriptB_path)
scriptb_module.b()
print "test2"
if __name__ == '__main__':
run()
我得到test1因此进程构建器正确执行初始python脚本A,正确解析参数并为scriptB提供正确的路径但是它无法调用函数scriptB.b。我认为问题在于它无法将scriptB作为模块导入,因为它是作为参数传递的。