问题
I generated an exe from Pyinstaller, this works perfectly when I double click it but when I try to run it via Task scheduler it never runs but in the history it shows "The operation completed successfully".
To be sure if it ran, I'm logging some text into a log file when the exe runs which never happens via Task scheduler.
Below is the simple snippet of my Python program.
import os
import threading
import sys
import time
from datetime import datetime
from dateutil import tz
#Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
logFilespath = 'logs'
if not os.path.exists(logFilespath):
os.makedirs(logFilespath)
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a file handler
todayDate = datetime.now()
todayDate = datetime.strftime(todayDate, '%Y%m%d')
handler = logging.FileHandler('logs/log' + str(todayDate) + '.log')
handler.setLevel(logging.INFO)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(handler)
logger.info('**** Starting KPI Calculations ****')
I'm using Python2.7 and tried with py2exe but with the same result.
回答1:
A simple way to resolve this:
1. Find the python executable in your system.
import sys
print("Python EXE: " + sys.executable)
In my case: "C:\users\USER\appdata\local\continuum\anaconda3\python.exe"
2. Select the path to your python code.
In my case: "C:\Users\USER\Documents\SandBox\test.py"
3. Open a notepad and write: 'start PYTHONPATH SCRIPTPATH' as in:
start C:\users\USER\appdata\local\continuum\anaconda3\python.exe C:\Users\USER\Documents\SandBox\test.py
4. Save this notepad as .bat in somewhere.
5. Schedule this .bat
The system will properly run the bat which will run the script.
来源:https://stackoverflow.com/questions/51948219/pyinstaller-generated-exe-doesnt-run-with-windows-task-scheduler