search

Home  >  Q&A  >  body text

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

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
怪我咯怪我咯2781 days ago1299

reply all(2)I'll reply

  • ringa_lee

    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);
        }
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦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.

    reply
    0
  • Cancelreply