我正在尝试制作一个 python 脚本(无限循环),使其每天从上午 9 点工作到 23:00 左右,并且一遍又一遍。我做了一些研究,最后提出了这段代码:
while True:
if dt.now().hour in range(9, 23):
if __name__ == "__main__":
""" Not important """
while True:
try:
""" bet_automation contains all the necessary code """
bet_automation()
except Exception as ex:
""" Catch all the error of bet_automation() and restart program """
print_error(ex)
time.sleep(5)
if not isinstance(ex, LoginTimeoutException):
try:
driver = get_driver()
filename = str(time.time())
driver.get_screenshot_as_file("errors/{}.png".format(filename))
with io.open("errors/{}.html".format(filename)) as f:
f.write(unicode(driver.page_source))
except:
pass
try:
quit_driver()
except:
pass
else:
sys.exit(0)
由此,脚本设法在 20.00 开始并正常工作。即使我提前运行它,它也只在 20.00 开始工作,这很好,但它不会在 21 点终止,这令人困惑。
我很清楚这可能是一个 super 简单和愚蠢的问题,但正如我所说,我是终极初学者。我让“专业”程序员编写了这个脚本,我正在尝试对其进行编辑和改进,我想自己做以了解整个过程。
非常感谢每一个见解,
非常感谢,
:)
最佳答案
您的代码包含两个循环。首先,外环。这个基本上是无关紧要的;如果您在 9:00 和 23:00 之间的某个时间启动程序,dt.now().hour in range(9, 23)
将计算为 True
,因此代码将进入内部(无限)循环。如果条件评估为 False
,程序将退出。因此,外部循环体只会执行一次。
然后是内循环。这个是无限的,一旦输入密码就永远无法破解。如果在某次迭代中 bet_automation()
没有抛出异常,则会在下一次迭代中再次执行。如果在某个迭代中 bet_automation()
确实 抛出错误,它会被简单地捕获并处理,然后循环将继续。
如果您希望代码在某个时刻停止,您需要在内部 循环中构建对当前时间的检查,如下所示:
while True:
try:
bet_automation()
if dt.now().hour not in range(9, 23):
break
(...)
关于python - 让python脚本在特定时间内每天运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630709/