Python时间延迟 [英] Python time delay

查看:204
本文介绍了Python时间延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我想知道如何在不暂停整个程序的情况下延迟程序的一部分。
我不一定擅长python,所以如果可以的话,如果可以给我一个相对简单的答案,那会很棒。

Alright, I want to know how to delay a portion of a program without pausing the entire program. I'm not necessarily good at python so if you could give me a relatively simple answer if possible, that would be great.

我想要一个每次调用此函数时,turtle都会在屏幕上画一个圆。

I want to have a turtle draw a circle on screen every time this function is called, this is what I have:

import time
from random import randint
turtle5 = turtle.Turtle()    

coinx = randint(-200, 200)
coiny = randint(-200, 200)

turtle5.pu()
turtle5.goto(coinx, coiny)
turtle5.pd()
turtle5.begin_fill()
turtle5.fillcolor("Gold")
turtle5.circle(5, 360, 8)
turtle5.end_fill()
time.sleep(1)
turtle5.clear()


推荐答案

您需要将要延迟的程序部分放在自己的线程中,然后

You need to put the part of the program you want to delay in its own thread, and then call sleep() in that thread.

我不确定您要在示例中执行的操作,所以下面是一个简单的示例:

I am not sure exactly what you are trying to do in your example, so here is a simple example:

import time
import threading

def print_time(msg):
    print 'The time %s is: %s.' % (msg, time.ctime(time.time()))

class Wait(threading.Thread):
    def __init__(self, seconds):
        super(Wait, self).__init__()
        self.seconds = seconds
    def run(self):
        time.sleep(self.seconds)
        print_time('after waiting %d seconds' % self.seconds)

if __name__ == '__main__':
    wait_thread = Wait(5)
    wait_thread.start()
    print_time('now')

输出:

The time now is: Mon Jan 12 01:57:59 2015.
The time after waiting 5 seconds is: Mon Jan 12 01:58:04 2015.

请注意,我们启动了将首先等待5秒的线程,但它并未阻止print_time('now')调用,而是在后台等待。

Notice that we started the thread that will wait 5 seconds first, but it did not block the print_time('now') call, rather it waited in the background.

编辑:

根据JF Sebastian的评论,使用threadin的简单解决方案g是:

From J.F. Sebastian's comment, the simpler solution with threading is:

import time
import threading

def print_time(msg):
    print 'The time %s is: %s.' % (msg, time.ctime(time.time()))

if __name__ == '__main__':
    t = threading.Timer(5, print_time, args = ['after 5 seconds'])
    t.start()
    print_time('now')

这篇关于Python时间延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆