I am trying to run a python script on Windows 10, the script should start automatically on background at system startup. So, I created a task in Task Scheduler with highest privileges, trigger: at startup, action: Program/script containing path to pythonw.exe and arguments containing path to script(in quotes). But still I am not able to run the task automatically at startup of the system,however the task starts running and works fine if I run it manually on Task Scheduler

The Code of the Python Script is as Follows:

import time
from datetime import datetime as dt
hosts_temp = r"D:\Python Udemy Course\Application3\hosts"
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = ""
website_list = ["www.facebook.com", "facebook.com", "www.twitter.com", "twitter.com"]

while True:
    if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 21):
        print("Working hours...")
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for website in website_list:
                if website in content:
                    file.write(redirect + " "+ website + "\n")
        print("Fun hours...")
        with open(hosts_path, 'r+') as file:
            content = file.readlines()
            for line in content:
                if not any(website in line for website in website_list):

When Running python from the task scheduler - the automation fails (but works manually) because of the environmental variables in path and user context. It fails because it doesn't know how to run it correctly from the automation side. Here is how to resolve the issue -

Create a .bat file that looks similar to the following to exectute your .py code. This calls the python exe directly. Your path/version may be different.

"c:\python27\python.exe" "C:\myPythonProgram.py"

Next, you will add the bat path to the action tab in task scheduler so that the path looks like:


Do not put in any values other the the program/script box.

  • Hi @Narzard, tried your solution but it didn't work, The task was ready at the startup of the system not running. – chabil kansal Jan 15 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.