简体   繁体   English

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

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

I am teaching myself python and I am trying to a code to open the cd drive at a certain time. 我正在自学python,并尝试编写代码以在特定时间打开CD驱动器。 For reasons of testing I have been using time.clock() because it only uses numbers, but I want to use time.ctime() so that the program will work at a specific time. 出于测试的原因,我一直在使用time.clock(),因为它只使用数字,但是我想使用time.ctime()以便程序在特定时间运行。 This is the code that I have so far. 这是我到目前为止的代码。

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()

I am using the print(x) function to monitor the code, and I set the range high enough that it won't stop before reaching the number of seconds the door should to open. 我正在使用print(x)函数监视代码,并且将范围设置得足够高,以使其在达到门应该打开的秒数之前不会停止。

Instead of for x in range(10**100): you could use 代替for x in range(10**100):您可以使用

while True:
    # do stuff forever

This loop will continue until you explicitly break out (or return for a function, raise an exception or quit the program etc). 该循环将一直持续到您明确break (或返回函数,引发异常或退出程序等)为止。

time.ctime() returns a string, which is not good for comparing to a given time. time.ctime()返回一个字符串,该字符串与给定时间进行比较time.ctime() Instead, I would suggest using the datetime module 相反,我建议使用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