简体   繁体   中英

Windows task scheduler and python logging module

I have a program which is running on daily basis. I would like to have a log created for each run of it. Here is the snip of code responsible for logging:

logging.basicConfig(filename = 'log.txt', level = logging.DEBUG, format = '%(asctime)s - %(levelname)s - %(message)s')

logging.debug('Start of program') # example logging

Everything runs perfectly fine as long as I launch it by .py file or .bat file (mouse clicking in file explorer). Unfortunately, when I put it on the schedule the program runs fine but log file doesn't get created.

I have tried multiple scheduler settings but the problem seems to be located in the code of the script.

Thanks for feedback!

I wanted to add the solution as an answer too, since this seems to be a somewhat common problem which has caused me some grief in the past.

When executing something from the Windows Task Scheduler the working directory of that process is not by default the path of the executable but some other directory. Eg when your Scheduler action calls C:\\sample.py this is not executed in C:\\ but C:\\Windows\\system32 (in my case).

You can verify this by adding a Scheduled Task calling a simple Python/Batch script which saves the active working directory to some file, such as this

import os

with open("C:\\cwd.txt", "w") as fh:
    fh.write(os.getcwd())

or this

echo %cd% >> C:\cwd.txt

This messes with any relative paths your program may contain and, I suspect, it has some more subtle issues that I have not been able to pin down yet.

Problems can be avoided by explicitly setting the optional 'Start in' path for your action: 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM