Java调用python脚本,脚本日志如何输入到日志文件中?如何实时获取脚本日志?
怪我咯
怪我咯 2017-04-18 10:22:33
0
2
1302

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
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
左手右手慢动作

Don’t use the redirection character in Runtime.exec(), instead use process.getInputStream() to get the log. For example:

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

1 Create sh file
cd /tmp && echo "/usr/bin/python /tmp/pytest.py >>/tmp/pylog.log 2>&1" >> pytest.sh
2 in java Execute the sh file
Execute Runtime.getRuntime().exec(“/usr/bin/sh /tmp/pytest.sh”)
3 in java.

PS: Remember to use absolute addresses for python and sh commands.
My terminals are /usr/bin/python and /usr/bin/sh. Remember to adjust the response of your own terminal.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template