0

is there any way to get a python script to write logs to 2 different locations: file and terminal? But it should only print logs to the terminal if I run it manually. Othwervise when it's run by something else, it should only write logs to a log file. is it possible at all?

Kurama
  • 569
  • 2
  • 6
  • 14
  • check if this helps you - http://stackoverflow.com/questions/24957734/start-python-script-with-cron-and-output-print-to-a-file – AlokThakur Dec 15 '16 at 08:49
  • Possible duplicate of [Checking for interactive shell in a Python script](http://stackoverflow.com/questions/6108330/checking-for-interactive-shell-in-a-python-script) – teppic Dec 15 '16 at 08:51

1 Answers1

1

You can use the isatty() method that returns True if your program is connected to a tty, else it returns False. So in your case you could code something like this:

import sys

if sys.stdin.isatty():
   # Logs put here will be displayed on terminal when you invoke the script via cli
else:
    with open("/testFile.txt", "w") as f:
        f.write('Logging in a file')    
kingJulian
  • 5,601
  • 5
  • 17
  • 30