培森的Blog Python Java调用CMD执行Python命令

Java调用CMD执行Python命令

        //&nbsp…

        // python 自动摘要程序
        String pythonVersion = PorpertiesUtil.PYTHON_CMD + " " + path + "chengxu//2.0文章自动摘要提取.py";
            
        doCmd(pythonVersion);

使用CMD执行命令后, 防止线程阻塞,  开启两个线程进行疏通

        public void doCmd(String cmd) throws Exception {
		final Process process = Runtime.getRuntime().exec(cmd);
		System.out.println("start run cmd=" + cmd);

		// 处理InputStream的线程
		new Thread() {
			@Override
			public void run() {
				BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String line = null;

				try {
					while ((line = in.readLine()) != null) {
						System.out.println("output: " + line);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		new Thread() {
			@Override
			public void run() {
				BufferedReader err = new BufferedReader(new InputStreamReader(
						process.getErrorStream()));
				String line = null;

				try {
					while ((line = err.readLine()) != null) {
						System.out.println("err: " + line);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						err.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		process.waitFor();
		System.out.println("finish run cmd=" + cmd);
	}

本文来自网络,不代表培森的Blog立场,转载请注明出处:https://blog.xupeisen.com/archives/39

作者: 培森

联系我们

联系我们

13262951234

在线咨询: QQ交谈

邮箱: admin@xupeisen.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部