运行 Python 后台脚本

Running Python script in the background

我创建了一个 Python 脚本来根据一天中的时间更改我的背景图片(Windows 10 个用户)。 如果当前时间超过日落时间,则显示特定图像,如果超过日出时间,则显示另一张。

sunrise/sunset 数据取自 Excel 电子表格的已发布来源。

我想要的是在后台使用此 Python 代码 运行,而不是每 30 秒创建一个 运行 任务计划程序作业。有没有更好的方法来处理下面的代码以实现这一点?

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)

对于乱七八糟的代码提前致歉。昨天是我第一天为这种目的编写代码。

你可以写

pythonw.exe code.py

这将 运行 后台代码,您需要从任务管理器中将其关闭 如果您希望此程序在计算机启动时启动,您可以在 shell:startup 中放置一个批处理文件并在那里写入

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

就是这样