Jython:在java 中调用python的py文件并获得输出流结果

在网上有很多方法来解决python文件找不到包的方法,我也试了试,但是不尽人意,于是脑洞大开尝试将python脚本编译为exe,再从java 中调用执行exe文件,并获取控制台输出流,获取输出文本。特此记录。(需要其他包来支持py文件的情况)

补充:在慕课高阶java编程课程中,了解到更轻便的方法,直接执行py文件(前提:无需导入其他库文件或者包)

可能我也有一些理解不当的地方,欢迎大家补充纠正!

部分代码:

@SuppressWarnings("resource")
	public void Spider() {
		String[] pra = { "", "", "", "" };

		try {
			String pythonFile = System.getProperty("user.dir") + "\\src\\Weather\\test.exe";
			pra[0] = pythonFile;
			String[] paramter = new String[] { pra[0] }; // 这里可以设置传入参数 pra[1] 等等,加入paramter 即可
			Process pr = Runtime.getRuntime().exec(paramter);
			BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));

			String call;
			int i = 0;
			while ((call = in.readLine()) != null) {
				this.info[i] = call;
				i++;
			}
			in.close();
			pr.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值