繁体   English   中英

有没有更好的循环代码的方法?

[英]Is there a better way to loop code?

我正在自学python,并尝试编写代码以在特定时间打开CD驱动器。 出于测试的原因,我一直在使用time.clock(),因为它只使用数字,但是我想使用time.ctime()以便程序在特定时间运行。 这是我到目前为止的代码。

import time
import ctypes
if(time.clock()==10):
    ctypes.windll.winmm.mciSendStringW("set cdaudio door open",
            None, 0, None)
for x in range(10**100):
    print(x)
    if(20>time.clock()>10):
        ctypes.windll.winmm.mciSendStringW("set cdaudio door open",
            None, 0, None)
        quit()

我正在使用print(x)函数监视代码,并且将范围设置得足够高,以使其在达到门应该打开的秒数之前不会停止。

代替for x in range(10**100):您可以使用

while True:
    # do stuff forever

该循环将一直持续到您明确break (或返回函数,引发异常或退出程序等)为止。

time.ctime()返回一个字符串,该字符串与给定时间进行比较time.ctime() 相反,我建议使用datetime模块

go_time = datetime.datetime(2014, 9, 3, 12, 30)
while True:
    now = datetime.datetime.now()
    if now >= go_time:
        # open the draw etc...
        quit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM