0

I have created a Python script to change my background image based on the time of the day (Windows 10 user). If the current time it's past the sunset time, then a specific image will be shown, if it's past the sunrise time, then there would be another one.

The sunrise/sunset data is being taken from a published source from an Excel spreadsheet.

What I want is to have this Python code running in the background instead of creating a Task Scheduler job to be ran every 30 seconds. Is there a better way to approach the code below in order to realize this?

from datetime import datetime
import pandas
import ctypes

file_path = "myfile.xlsx"
data = pandas.read_excel(file_path, header=0) #Column lines on line 0

#Today as day number
day = datetime.now().timetuple().tm_yday

#Today's parameters
sunrise = data["sr"][day-1] #sr is a column name in the Excel spreadsheet; Minus 1 to account for 0 based indexing; 
sunset = data["ss"][day-1] #ss is a column name in the Excel spreadsheet; Minus 1 to account for 0 based indexing; 

#Time right now
now = datetime.now().time()

#Setting up the day_night variable depending on the now variable
if now > sunrise and now < sunset:
    day_night = 'day'
else:
    day_night = 'night'

#The path to the wallpapers being used
path = 'C:\\wallpapers\\'+ day_night +'.jpg'
SPI_SETDESKWALLPAPER = 20

#Function to change the wallpaper
def changeBG(path):
    ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, path, 3)

changeBG(path)

Sorry in advance for the messy code. Yesterday was my first day writing code for this kind of purposes.

instaspam
  • 32
  • 2
  • 8
  • 1
    What's wrong about using `Task Scheduler`, which is meant to run something periodically in the **background** on Windows ? – Maurice Meyer Apr 25 '21 at 07:45
  • I haven't used Task Scheduler so far, but I was thinking that having this script ran every 30 seconds will require some resources. I haven't tried it yet, to be honest to see how it behaves. – instaspam Apr 25 '21 at 07:53

1 Answers1

1

you can write

pythonw.exe code.py

this will run the code in the background and you will need to turn it off from task manager if you want this program to start when the computer starts you can place a batch file in shell:startup and write there

pythonw.exe C:\path\To\Code.py

and that's it

R3tr0
  • 50
  • 8
  • Thank you for your answer. One question: where is `pythonw.exe code.py` supposed to be written? Python code or batch file? – instaspam Apr 25 '21 at 07:55
  • ```pythonw.exe code.py``` can be run from the cmd as long as python is in the path in the batch file writer ```pythonw.exe PATHTOFILE://``` and that's it – R3tr0 Apr 25 '21 at 09:17