6

I have a python program that uses the logging module to output data to a text file, the problem I have is that the output to the text file works fine when I run the script in PyCharm (the 1-10 values are output to both the console screen and written to Log_Test_File.txt), but when I run the script from the command line only the console output appears (with nothing written to the *.txt file). This occurs in both Ubuntu or on my Raspberry Pi.

I'll be running the script on the Pi automatically on start-up (as sudo), is there a way to configure either the Pi or the script so that the text output works correctly?

#!/usr/bin/python
# -*- coding: utf-8 -*-

import logging

logging.basicConfig(filename="Log_Test_File.txt",
                level=logging.DEBUG,
                format='%(levelname)s: %(asctime)s %(message)s',
                datefmt='%m/%d/%Y %I:%M:%S')

i=0
while i<10:
    logging.info("Logging test: {}".format(i))
    i+=1
StepUp
  • 36,391
  • 15
  • 88
  • 148
AdamDynamic
  • 761
  • 6
  • 15
  • 29
  • Please be more specific about the problem and any errors. _"...works fine when I run the script in PyCharm but not when I run the script from the command line"_ is vague. – ChrisP Apr 24 '16 at 18:04

1 Answers1

3

The code you have provided runs well.

If you have problems with finding the log file being properly created, the reasons might be:

  • not having permission to create the log file
  • the script does not run at all

If you plan to run the script as long running service, I would recommend to skip creating explicit log file and rather log to stdout. The output sent to stdout is easy to see, capture and process by program controlling execution of the script (e.g. supervisord, systemd etc.).

Another option would be to log to syslog directly, but this could become more complicated as your program would have to know on it's own, what values to use for identifying the process. This is mostly simpler for process manager then for the program itself.

Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98
  • Thanks for the response - I'd prefer to use the logging module if possible (I'm able to change the level of logging from DEBUG to INFO for example which is convenient), any idea what the permissions issue might be or how I would change it? – AdamDynamic Apr 24 '16 at 21:56
  • @AdamDynamic You can log to stdout or stderr with standard logging, just using StreamHandler. Regarding permission problems - just make sure the user, who runs the script is able creating the file where is log to be written - e.g. by simple `$ touch the_log_file.log`. If it fails, use `chown` or `chmod`. – Jan Vlcinsky Apr 24 '16 at 22:01