Python睡眠时不会干扰脚本?

Aus*_*inM 5 python time sleep function

嘿我需要知道如何在不干扰当前脚本的情况下在Python中睡觉.我尝试过使用time.sleep()它会使整个脚本都处于睡眠状态.

比如说


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

func1()

我希望它立即在这里打印Do stuff,然后等待10秒并在这里打印更多的东西.

unh*_*ler 7

从字面上解释您的描述,您需要在调用之前放置print语句func2().

但是,我猜你真正想要的是func2()一个后台任务,它允许func1()立即返回而不是等待func2()完成它的执行.为此,您需要创建一个要运行的线程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")
Run Code Online (Sandbox Code Playgroud)

  • @delnan:是的.[multiprocessing](http://docs.python.org/library/multiprocessing.html#module-multiprocessing)将是以不同方式提供相同功能的另一种选择.如果我们想要另一个不切实际的解决方案,我确信有些东西会涉及到可行的鸽子. (2认同)

jfs*_*jfs 6

你可以使用threading.Timer:

from __future__ import print_function
from threading import Timer

def func1():
    func2()
    print("Do stuff here")
def func2():
    Timer(10, print, ["Do more stuff here"]).start()

func1()
Run Code Online (Sandbox Code Playgroud)

但正如@unholysampler已经指出的那样,写一下可能会更好:

import time

def func1():
    print("Do stuff here")
    func2()

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

func1()
Run Code Online (Sandbox Code Playgroud)