How to run Python script in background [automatically] on Windows Startup
I wanted to make my python script run automatically on starting up the PC , and here is how you can do it , in background ;-)
To run the Script in Background
You can use a batch script / VBScript to launch your Python file. I used a VBScript to do so. Make a new directory and create launcher.vbs here.
Set oShell = CreateObject (“WScript.Shell”)
oShell.run “pythonw main.py”
Here
- WScript.Shell just provides access to OS Shell methods.
- ‘pythonw’ instead of ‘python’ runs our main.py (present in the same directory) in background.
Note : pythonw executes the script in background and nothing goes to stdout, so you need to make sure to catch exceptions before executing the file with it.
I’ve created main.py which will create a text file just to verify the execution.
from datetime import datetime
now = datetime.now()
dt_string = now.strftime(“%d/%B/%Y, %H:%M:%S”)
with open(‘Yayy.txt’,’w’) as f:
f.write(dt_string)
Now you can run the launcher.vbs and you’ll see a new text file in the same directory. Check your syntax if the file is not created.
The first step is done. Now your program can run in background. We just need to launch it automatically on startup.
To launch the Script automatically on Startup
There are more than one methods to do this in Windows. Using Task Scheduler is one of them. But it didn’t work for me. So ,a simple thing that worked for me (Windows 10 Pro) was this :
- Copy the launcher.vbs file that we created.
- Press Win + R and type shell:startup and press enter.
- In the directory that opens up, paste the shortcut of .vbs file.
The script is triggered after 10–15 seconds after the PC starts up.
Restart and check the text file in the main directoy, it should show an updated time.
That is it. I don’t know the exact problem why things did not work for me, so when I found simple a method that worked, wrote it down.