0

I want to execute a python script through java. 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. 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

Python script

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

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

    }

}
Padmasankha
  • 103
  • 1
  • 13
  • the question is not specific enough. it would be useful to know where you run your java and python. – Holm Jul 22 '19 at 07:51
  • @HungUnicorn application running on a apache server. python scripts are also deploying in the same server. Script executing part works fine. only problem is the saving logs in to a file – Padmasankha Jul 22 '19 at 07:56
  • 2
    maybe it runs in different folder then you expect so it save log in different folder then you expect. Use `/full/path/to/log_test.log` – furas Jul 22 '19 at 08:06
  • @furas I tried that also. It didn't work – Padmasankha Jul 22 '19 at 08:41
  • so maybe java doesn't execute it or get error, or use old version without full path ? If you get output from script then you should use `print()` in Python to display information and Java should get it and show it to you. This way you can test both programs - it is "print debugging". – furas Jul 22 '19 at 08:45
  • @furas yes. it works with full path. It was my mistake. Thank you – Padmasankha Jul 22 '19 at 09:23

1 Answers1

0

Change Python path and script path to absolute path

And change the file path of logging.FileHandler to the absolute path.

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
Seha Jyang
  • 11
  • 1
  • 3