[英]Save logs in to a file by executing python code through java
I want to execute a python script through java.我想通过java执行一个python脚本。 I used below sample code for that.我为此使用了以下示例代码。 the problem is when I execute python script through commandline it save logs in to log_test.log file.问题是当我通过命令行执行 python 脚本时,它会将日志保存到 log_test.log 文件中。 but when I execute from java logs doesn't write in to the log file I'm using python 3.7 and java 1.8但是当我从 java 日志执行时没有写入日志文件我使用的是 python 3.7 和 java 1.8
Python script Python脚本
import logging
logger = logging.getLogger('log_test')
logger.setLevel(logging.INFO)
fh = logging.FileHandler('log_test.log')
fh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.info('info message')
Java code Java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException, IOException {
Process p = Runtime.getRuntime().exec("python ./log_test.py");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("output");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
}
Change Python path and script path to absolute path将 Python 路径和脚本路径更改为绝对路径
And change the file path of logging.FileHandler
to the absolute path.并将logging.FileHandler
的文件路径改为绝对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.