Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

Java调用python脚本,脚本日志如何输入到日志文件中?如何实时获取脚本日志?

Java调用python脚本遇到的两个问题,求教:

  • 1、Java调用python脚本,python脚本不会输出日志到日志文件;
    但是单独运行python脚本会输出日志文件,为什么?怎么解决?

  • 2、Java调用python脚本,只会在脚本执行结束后才可以一次性获取脚本日志信息,怎么实现实时获取脚本执行日志?

相关代码和脚本

终端直接执行,会生成日志文件
python /tmp/pytest.py >>/tmp/pylog.log 2>&1
Java调用,不会新建生成日志文件

···
Runtime.getRuntime().exec(“python /tmp/pytest.py >>/tmp/pylog.log 2>&1”)
···

python脚本
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import logging
import time

logging.basicConfig(level=logging.DEBUG)

for num in range(0, 3):
    time.sleep(1)
    logging.info('logging 当前序号 :' + str(num) )
    print' print当前序号 :', num

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不要在Runtime.exec()里使用重定向符,而是用process.getInputStream()获得日志。例如:

    Process process = Runtime.getRuntime().exec("python /tmp/pytest.py");
    try (FileOutputStream out = new FileOutputStream("/tmp/pylog.log")) {
        Streams.copy(process.getInputStream(), out);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...