Java、Python程序中命令行调用Python算法脚本

Java程序通过命令行形式调用Python脚本

主函数可以这样写 代码片.

//写调用python脚本的cmd 例如python main.py -f filename
public static void main(String[]args){
	String cmd = "python main.py";
	String results = algorithm(cmd);
	System.out.println(results);
}

ps:保证在命令行窗口下可以执行编辑的cmd;

下面展示调用函数的 代码片.

// 调用脚本函数
public static String algorithm(String cmd) {
        Process process;
        try {
            process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            String inStr = consumeInputStream(process.getInputStream());
            String errStr = consumeInputStream(process.getErrorStream());
            return inStr;
        } catch (Exception e) {
            return "";
        }
    };

下面展示consumeInputStream函数的 代码片.

// 返回脚本执行结果
private static String consumeInputStream(InputStream inputStream) throws IOException {
        BufferedReader inBuffer = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder output = new StringBuilder();
        String line = null;
        while ((line = inBuffer.readLine()) != null) {
            output.append(line);
        }
        inBuffer.close();
        return output.toString();
}

Python程序调用命令行

主函数可以这样写 代码片.

//写调用python脚本的cmd 例如python main.py -f filename
import subprocess
def main():
	cmd = 'python main.py'
	p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	//保存结果
	p.wait()
	result_lines = p.stdout.readlines()   # 从子进程 p 的标准输出中读取所有行,并储存在一个list对象中
	for line in result_lines:
		print(line.strip())
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值