You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何用变量动态设置schedule模块的day属性?

解决schedule模块动态指定星期属性的问题

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:20:06