简体   繁体   中英

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. 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. 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.

Instead of for x in range(10**100): you could use

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

time.ctime() returns a string, which is not good for comparing to a given time. Instead, I would suggest using the datetime module

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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