0

My python script produces a log file with lines of logging when I run it from Spyder, but when I run it outside of Spyder (e.g. in the command window, or as an executable), the log file is produced but remains empty.

I confirmed that I'm using full file paths to specify the log file. I understand that using basicConfig doesn't always work as expected, so I followed the answer provided here. A simplified version of my script is shown below:

# Example inputs
workdir = 'c:\Users\xx\work'
log_file = 'log_2.txt'

# Initialize logging functionality
fileh = logging.FileHandler(os.path.join(workdir, log_file), 'w')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fileh.setFormatter(formatter)
fileh.setLevel(logging.DEBUG)

log = logging.getLogger()  # root logger
for hdlr in log.handlers[:]:  # remove all old handlers
    log.removeHandler(hdlr)
log.addHandler(fileh)  # set the new handler

# Rest of code including log messages (removed rest of script here, only leaving logging-related text)
logging.info('Here is a log message.')
logging.debug('Here is another log message.')

# At the end of the script
logging.shutdown()

Most related questions are when someone can't find the log file that's being written. However, in this case, the log file is created but not written to.

Can someone advise on how this code needs to be modified to also work outside of Spyder?

Nena
  • 23
  • 3

0 Answers0