Python的睡眠不会干扰脚本?

编程入门 行业动态 更新时间:2024-10-26 06:29:43
本文介绍了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的睡眠不会干扰脚本?

本文发布于:2023-10-08 02:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   干扰   睡眠   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!