Python的睡眠不会干扰脚本? [英] Python sleep without interfering with script?

查看:265
本文介绍了Python的睡眠不会干扰脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我需要知道如何在不干扰当前脚本的情况下睡在Python中。我尝试过使用 time.sleep(),但它会让整个脚本休眠。

例如

  
进口时间
def func1():
func2()
print(做这里的东西)
def func2():
time.sleep(10)
print(在这里做更多的事情)



func1()


我希望它立即打印在这里做的东西,然后等待10秒钟,然后打印在这里做更多的东西。

解决方案

从字面上理解您的描述,您需要在调用 func2()



然而,我猜你真正想要的是 func2()到后台任务,它允许 func1()立即返回,而不是等待 func2()来完成它的执行。为此,您需要创建一个线程来运行 func2()

 进口时间
进口线程

def func1():
t = threading.Thread(target = func2)
t.start()
print(做这里的东西)
def func2():
time.sleep(10)
print(在这里做更多的事情)

func1()
print(func1 has returned)


Hey I need to know how to sleep in Python without interfering with the current script. I've tried using time.sleep() but it makes the entire script sleep.

Like for example


import time
def func1():
    func2()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()

I want it to immediately print Do stuff here, then wait 10 seconds and print Do more stuff here.

解决方案

Interpreting your description literally, you need to put the print statement before the call to func2().

However, I'm guessing what you really want is for func2() to a background task that allows func1() to return immediately and not wait for func2() to complete it's execution. In order to do this, you need to create a thread to run func2().

import time
import threading

def func1():
    t = threading.Thread(target=func2)
    t.start()
    print("Do stuff here")
def func2():
    time.sleep(10)
    print("Do more stuff here")

func1()
print("func1 has returned")

这篇关于Python的睡眠不会干扰脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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