Python中如何用变量动态设置schedule模块的day属性?
Hey there! No worries about terminology—we’ve all fumbled through new libraries as Python beginners 😊 Let’s break down your problem and fix that error.
问题原因
When you write schedule.every().dayArray[i], Python thinks you’re trying to access an attribute named dayArray directly on the Job object returned by every()—which doesn’t exist, hence the AttributeError. The .sunday/.monday syntax is accessing pre-defined attributes of the Job object, and you can’t use a variable name directly with dot notation like that.
解决方案:使用getattr()函数
Python’s built-in getattr() function is exactly what you need here. It lets you dynamically access an object’s attribute using a string name. Here’s how to adjust your code:
import schedule def job(): print("Scheduled job executed!") dayArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] # 假设xlsxSheet是你已加载的Excel工作表对象 for i in range(0, 7): # 注意:原range(0,6)会漏掉最后一个周六,这里调整为7覆盖全部星期 time_value = str(xlsxSheet.cell_value(i+18, 1)) if time_value != 'NA': # 用getattr动态获取对应星期的属性 getattr(schedule.every(), dayArray[i]).at(time_value).do(job)
为什么这能行?
getattr(schedule.every(), dayArray[i])会把dayArray[i]对应的字符串(比如'sunday')作为属性名,从Job对象上获取对应的属性——这和直接写schedule.every().sunday的效果完全一致。- 我们调整了循环范围到
range(0,7),确保你的星期数组里的所有元素都会被遍历到。
额外小贴士
- 确认
dayArray里的字符串和schedule模块要求的属性名完全匹配(这里的小写完整星期名是正确的)。 - 确保从Excel读取的时间字符串是
HH:MM格式(比如'8:00'),schedule的at()方法需要这种格式才能正确识别。
内容的提问来源于stack exchange,提问作者ninbura

