Running a Python script for a user-specified amount of time

后端 未结 3 1870
你的背包
你的背包 2020-12-01 16:47

I\'ve just started learning Python today. I\'ve been reading a Byte of Python. Right now I have a project for Python that involves time. I can\'t find anything relating to t

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 16:55

    Try time.time(), which returns the current time as the number of seconds since a set time called the epoch (midnight on Jan. 1, 1970 for many computers). Here's one way to use it:

    import time
    
    max_time = int(raw_input('Enter the amount of seconds you want to run this: '))
    start_time = time.time()  # remember when we started
    while (time.time() - start_time) < max_time:
        do_stuff()
    

    So we'll loop as long as the time since we started is less than the user-specified maximum. This isn't perfect: most notably, if do_stuff() takes a long time, we won't stop until it finishes and we discover that we're past our deadline. If you need to be able to interrupt a task in progress as soon as the time elapses, the problem gets more complicated.

提交回复
热议问题