1、Java调用python脚本,python脚本不会输出日志到日志文件;
但是单独运行python脚本会输出日志文件,为什么?怎么解决?
2、Java调用python脚本,只会在脚本执行结束后才可以一次性获取脚本日志信息,怎么实现实时获取脚本执行日志?
python /tmp/pytest.py >>/tmp/pylog.log 2>&1
···
Runtime.getRuntime().exec(“python /tmp/pytest.py >>/tmp/pylog.log 2>&1”)
···
#!/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
ringa_lee2017-04-18 10:24:33
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);
}
伊谢尔伦2017-04-18 10:24:33
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.