精华内容
下载资源
问答
  • python time.sleep()-睡眠线程还是进程?它会阻止线程。如果查看Python源代码中的Modules / timemodule.c,您会看到在调用中floatsleep(),睡眠操作的实质部分包含在Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS块...

    python time.sleep()-睡眠线程还是进程?

    它会阻止线程。如果查看Python源代码中的Modules / timemodule.c,您会看到在调用中floatsleep(),睡眠操作的实质部分包含在Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS块中,允许其他线程继续执行当前线程睡觉。你也可以用一个简单的python程序来测试它:

    import time

    from threading import Thread

    class worker(Thread):

    def run(self):

    for x in xrange(0,11):

    print x

    time.sleep(1)

    class waiter(Thread):

    def run(self):

    for x in xrange(100,103):

    print x

    time.sleep(5)

    def run():

    worker().start()

    waiter().start()

    哪个会打印:

    >>> thread_test.run()

    0

    100

    >>> 1

    2

    3

    4

    5

    101

    6

    7

    8

    9

    10

    102

    ps:下面看下Python Sleep休眠函数

    Python 编程中使用 time 模块可以让程序休眠,具体方法是time.sleep(秒数),其中”秒数”以秒为单位,可以是小数,0.1秒则代表休眠100毫秒。

    # 例1:循环输出休眠1秒

    import time

    i = 1

    while i <= 3:

    print i # 输出i

    i += 1

    time.sleep(1) # 休眠1秒1234567

    # 例2:循环输出休眠100毫秒

    import time

    i = 1

    while i <= 3:

    print i # 输出i

    i += 1

    time.sleep(0.1) # 休眠0.1秒

    总结

    以上所述是小编给大家介绍的python time.sleep()是睡眠线程还是进程,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对聚米学院网站的支持!

    如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

    展开全文
  • Python通过time.sleep()函数使此任务毫不费力。Ť他的文章中介绍这个功能的功能,连同其应用程序一起。在继续之前,让我们快速看一下本文涵盖的主题:让我们开始吧。:)为什么要使用Python time.sleep()?睡眠功能在...

    有时,我们需要程序或程序的各个部分在短时间内执行。Python通过time.sleep()函数使此任务毫不费力。Ť他的文章中介绍这个功能的功能,连同其应用程序一起。

    在继续之前,让我们快速看一下本文涵盖的主题:

    让我们开始吧。:)

    为什么要使用Python time.sleep()?

    睡眠功能在我们要停止程序流并让其他执行发生的情况下起着非常重要的作用。该函数在python的两个版本(即2和3)中都有定义。它属于Python的时间模块。基本上,这会增加执行延迟,并且只会暂停当前线程,而不会暂停整个程序。

    时间模块

    Python的time模块中提供了Python time.sleep()函数。在使用此Python函数之前,您需要使用以下命令导入此模块:

    import time

    导入此模块后,即可使用time.sleep()函数。语法如下:

    句法:

    睡眠(秒)

    如您所见,它需要一个参数,即秒。在执行过程中,这基本上会引起这么多秒的延迟。该函数的返回值是void。

    现在让我们举一些例子来了解此功能的工作原理。

    Python time.sleep()示例:

    考虑下面的示例,该示例在输出之间引起一秒的延迟。

    例子:

    import time # import time module

    sleep_time = 1 # time to add delay after first print statement

    print('Hello')

    time.sleep(sleep_time) # sleep time

    print('Edureka!')

    输出:

    如果执行了以上代码,则会在程序中增加延迟,因此,下一条语句将在1秒后执行。对于确切的延迟,您还可以将浮点值传递给该函数。例如,如果经过了0.1秒,则将延迟100毫秒。

    这是另一个示例,它将在执行程序之前和之后返回系统时间。

    例子:

    # sleep demonstration

    import time

    # Start time

    print("The time of code execution begin is : ", end ="")

    print(time.ctime())

    # haulting program

    time.sleep(6)

    # end time

    print("The time of code execution end is : ", end ="")

    print(time.ctime())

    输出:

    开始执行代码的时间是:Sun Jun 23 22:36:19 2019开始执行代码的时间是:Sun Jun 23 22:36:25 2019进程返回0(0x0)执行时间:6.089 s按任意键继续。。。

    睡眠示例:

    以下是睡眠功能的示例:

    import time

    startTime = time.time()

    for i in range(5, 10):

    print(i)

    # making delay for 1 second

    time.sleep(1)

    endTime = time.time()

    elapsedTime = endTime - startTime

    print("Elapsed Time = %s" % elapsedTime)

    输出:

    56789

    经过的时间= 5.006335258483887进程返回0(0x0)执行时间:5.147 s

    每次停止执行1秒钟,因此完整执行耗时5秒。另外,执行所需的额外时间是系统对程序进行后台操作的时间。

    python sleep()的不同延迟时间

    根据所需的输出,可以在Python中的程序执行之间添加不同的延迟时间。以下代码演示了如何做到这一点:

    例子:

    import time

    for i in [1, 0.1, 2, 0.3]:

    print("I will sleep for %s" % i, end='')

    print(" seconds")

    time.sleep(i)

    输出:

    我要睡1秒

    我要睡0.1秒

    我要睡2秒

    我要睡0.3秒

    进程返回0(0x0)执行时间:3.538 s

    惰性打印:

    如果要以精美的方式打印某些内容,可以使用以下sleep()函数进行打印:

    # importing time module

    import time

    message = "Some fancy character printing!"

    for i in message:

    print(i)

    time.sleep(0.3)

    如果执行上面的代码,您会发现每个字符的打印延迟,看起来很花哨。

    Python线程睡眠

    在多线程环境中,sleep()被证明是非常重要的,因为它在执行时会在正在执行的当前线程中增加延迟。

    例子:

    import time

    from threading import Thread

    class Runner(Thread):

    def run(self):

    for x in range(0, 7):

    print(x)

    time.sleep(2)

    class Delay(Thread):

    def run(self):

    for x in range(106, 109):

    print(x)

    time.sleep(7)

    print("Staring Runner Thread")

    Runner().start()

    print("Starting Delay Thread")

    Delay().start()

    print("Done")

    以下是上面的线程示例的输出:

    f35d29aa858a6bae26b30c375752987c.png

    输出:

    如果执行该程序,您会注意到整个程序并没有停止,而是只有当前正在执行的线程才继续运行,然后尝试一下。

    应用 :

    此方法有很多应用程序,例如,我们可以使用它来创建漂亮的用户界面,以某种精美的方式打印菜单或标题,但是,重要的应用程序之一是暂停要执行的后台进程在一定间隔内。

    应用实例:

    import time

    string = "Edureka!"

    print_string = ""

    for i in range(0, len(string)):

    print_string = print_string + string[i]

    print(print_string)

    time.sleep(2)

    输出:

    E

    Ed

    Edu

    Edur

    Edure

    Edurek

    Edureka

    Edureka!

    正如我们已经看到的那样,sleep函数会使程序暂停一段时间,而Python的时间模块就派上用场了。让我们看一下如何从用户那里获取输入并动态使用相同的功能。

    动态睡眠示例

    这是一个睡眠示例,该示例利用来自用户的输入在两个打印功能之间添加延迟,并打印执行打印功能所花费的时间,以下示例基于Python3.x。

    import time

    def sleeper():

    while True:

    num = input('Enter wait time: ')

    try:

    num = float(num)

    except ValueError:

    print('Number only.n')

    continue

    # Run our time.sleep() command,

    # and show the before and after time

    print('Before: %s' % time.ctime())

    time.sleep(num)

    print('After: %sn' % time.ctime())

    try:

    sleeper()

    except KeyboardInterrupt:

    print('nnException Exiting.')

    exit()

    输出:

    输入等待时间:1之前:Sun Jun 23 22:44:13 2019之后:Sun Jun 23 22:44:14 2019输入等待时间:3之前:Sun Jun 23 22:44:16 2019之后:Sun Jun 23 22: 2019年44月19日

    准确性

    如果要在更短的时间内停止执行,则此函数受操作系统的限制,因为此函数使用操作系统sleep()函数,因此在Linux中,等待时间可以比Windows短。

    概括

    在上面的文章中,我们介绍了python中的sleep()方法,该方法主要用于增加程序执行的延迟,此程序包位于Python的时间模块中,该模块基本上使用底层操作系统的sleep()函数。我们还介绍了一些有关如何使用此功能的代码示例,并介绍了睡眠应用程序。演示了使用该功能的理想方式以及它在线程环境中的工作方式。

    展开全文
  • I think this is going to be one of those simple-when-you-see-it problems, but it has got me baffled.[STOP PRESS: I was right.... See the answers.]I am using Python's unittest framewor...

    I think this is going to be one of those simple-when-you-see-it problems, but it has got me baffled.

    [STOP PRESS: I was right. Solution was found. See the answers.]

    I am using Python's unittest framework to test a multi-threaded app. Nice and straight forward - I have 5 or so worker threads monitoring a common queue, and a single producer thread making work-items for them. The producer thread is being triggered by a test-case.

    In this test, only one task is being put on the queue. The processing it does is in the test is just a stub for the real processing, so the worker thread does a 5 second-sleep to simulate the elapsed time before the task will really be done, and the thread will be ready to get another task.

    To the snippet of code is:

    logging.info("Sleep starting")

    time.sleep(5)

    logging.info("Waking up")

    Now the weird part. I see the "Sleep starting" log message, but not the Waking up message. The program locks up and doesn't respond to Keyboard Interrupt (CTRL+C). CPU load is very low.

    I see the same problem in Windows and Ubuntu (Python 2.6.2).

    I have pondered if an exception is occurring and being hidden, so I add "print 1/0" between the first and second line - I see the Division By Zero error being raised. I move it to after the sleep, and I never see the message.

    I figured "Okay, maybe the other thread is trying to log something very very large at the same time, and it is still buffering. What is it doing?"

    Well, by this time, the test has returned to the unittest, where it is pausing waiting for the thread to get going before testing the system's state.

    logging.info("Test sleep starting")

    time.sleep(0.25)

    logging.info("Test waking up")

    Wow, that looks familiar. It is freezing in exactly the same way! The first log message is appearing, the second isn't.

    I have recently done a significant rewrite of the unit so I can't claim "I didn't touch anything", but I can't see anything untoward in my changes.

    Suspicious areas:

    I am including using Threading.Lock (because I don't know how to reason about GIL's safety, so I stick to what I know. I see nothing "deadlocky" about my code.

    I am new to Python's unittest framework. Is there something it does with redirecting logging or similar that might simulate these symptoms?

    No, I haven't substituted a non-standard time module!

    What would prevent a thread from waking up? What else have I missed?

    解决方案

    Sigh.

    Worker Thread #1 is sleeping, and waking up afterwards. It is then going to log the wake message, and is blocked. Only one thread can be logging at a time.

    UnitTest Thread is sleeping, and waking up afterwards. It is then going to log the wake message, and is blocked. Only one thread can be logging at a time.

    Worker-Thread-Not-Previously-Mentioned-In-The-Question #2 was quietly finishing the processing the PREVIOUS item in the queue, while the first Worker Thread was sleeping. It got to a log statement. One of the parameters was an object, and str() was implicitly called. The str() function on that object had a bug; it deadlocked when it accessed some of its data members. The deadlock occured while being processed by the logging function, thus keeping the logging thread-lock, and making it appear like the other threads never woke up.

    The division by zero test didn't make a difference, because the result of it was an attempt to log.

    展开全文
  • I'm performing realtime data processing + display, and I hit our database every 60 ... I'd like to not use time.sleep() for waiting every 60 seconds, as it removes control from me (namely REPL ac...

    I'm performing realtime data processing + display, and I hit our database every 60 seconds. I'd like to not use time.sleep() for waiting every 60 seconds, as it removes control from me (namely REPL access to variables, which isn't necessary but nice) and freezes matplotlib charts.

    Is there an alternative? Ideally, something that would initially give control to the user, and after 60 seconds, take control away, run some code, and update a plot, then give control back to the user. (When I say control, I mean REPL control).

    Any ideas?

    解决方案

    If you don't need to take away user control, there's a very easy way to do this: Create a threading.Timer.

    What you want to do is take the "continuation" of the function—that is, everything that would come after the time.sleep—and move it into a separate function my_function, then schedule it like this:

    threading.Timer(60, my_function).start()

    And at the end of my_function, it schedules a new Timer with the exact same line of code.

    Timer is a pretty clunky interface and implementation, but it's built into the stdlib. You can find recipes on ActiveState and modules on PyPI that provide better classes that, e.g., run multiple timers on one thread instead of a thread per timer, let you schedule recurring calls so you don't have to keep rescheduling yourself, etc. But for something that just runs every 60 seconds, I think you may be OK with Timer.

    One thing to keep in mind: If the background job needs to deal with any of the same data the user is dealing with in the REPL, there is a chance of a race condition. Often in an interactive environment (especially in Python, thanks to the GIL), you can just lay the onus on the user to not cause any races. If not, you'll need some kind of synchronization.

    Another thing to keep in mind: If you're trying to do GUI work, depending on the GUI you're using (I believe matplotlib is configurable but defaults to tkinter?), you may not be able to update the GUI from a background thread.

    But there's actually a better solution in that case anyway. GUI programs have an event loop that runs in some thread or other, and almost every event loop ever design has a way to schedule a timer in that thread. For tkinter, if you have a handle to the root object, just call root.after(60000, my_function) instead of threading.Timer(60, my_function).start(), and it will run on the same thread as the GUI, and without wasting any unnecessary resources.

    展开全文
  • pythontime.sleep()有多准确?

    千次阅读 2020-12-29 04:24:20
    time.sleepfunction的准确性取决于底层操作系统的睡眠准确度。 对于非实时操作系统,就像一个股票Windows,你可以睡的最小时间间隔是10-13ms。 当在10-13ms以上时,我已经看到准确的睡眠时间在几毫秒内。更新:就像...
  • 上一章Python教程请查看:python3时间time模块sleep()函数在给定的秒数内挂起(等待)当前线程的执行。Python有一个名为time的模块,它提供了几个有用的函数来处理与时间相关的任务。其中一个流行的函数是sleep()。...
  • Python中的time.sleep()

    千次阅读 2021-02-03 10:04:00
    在本教程中,我们将学习time.sleep()方法。time.sleep()方法用于在特定时间内停止程序的执行。它是一个参数,即以秒为单位的时间。它将停止执行直到给定的秒数。让我们看一个简单的例子。执行以下代码时观察时间延迟...
  • 我从没想过,所以我写了这个剧本:import timewhile True:print "loop"time.sleep(0.5)只是个测试。使用strace -o isacontextswitch.strace -s512 python test.py运行此命令将在循环中提供此输出:write(1, "loop\n...
  • timepython带的非内置库,使用时需要import,主要用于处理和时间相关的操作。time.sleep用于给定时间内挂起(等待)当前线程的执行。time.sleep() 函数的例子:import timefor i in [1,3,5,7,9]:time.sleep(2)print...
  • 所以我在python中制作了一个reddit机器人,使用下面的代码repository是的。而且工作正常。但根据reddit的指导方针,我只能每10分钟发表一次评论。所以我用的是for在这里循环,代码的最后一部分如下:i=1for submission ...
  • time.sleep(0.001) 不要和cv2.wai ke混淆了,那个单位是毫秒;
  • 原标题:time.sleep()在python线程中的使用python学习 Python中的时间除了可以计算外,在延迟和暂停方面也有所涉及。之前学爬虫的时候用的是暂停功能,那么在多线程中为了使线程之间的有序运行,我们通常会使用time....
  • time.sleep(0.001) et = time.time() print('dt={dt}'.format(dt=et - st)) 返回结果: dt=0.001966238021850586 dt=0.001010894775390625 dt=0.0020058155059814453 dt=0.0010018348693847
  • 问题描述使用time做定时任务,但是一直会有一段时间被跳过,下面是我设置5分钟打印一次的日志。问题出现的环境背景及自己尝试过哪些方法原来以为是每次sleep的时间比较长(原设置为睡58*60),后面改成上面的sleep(1)...
  • 有时候,我们想实现一个非常简单的定时功能,例如:让一个程序每天早上 8 点调用某个函数但我们又不想安装任何第三方库,也不会使用 crontab 或者任务计划功能,就想使用纯 Python 来实现可能有同学会这样写代码:...
  • 如果查看Python源代码中的Modules / timemodule.c,您会看到在调用中floatsleep(),睡眠操作的实质部分包含在Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS块中,允许其他线程继续执行当前线程睡觉。你也可以用一个...
  • 使用start和join代替run:import multiprocessing, sys, timedef f(icount, _sleepTime = 1):for i in range(icount):time.sleep(_sleepTime)print(_sleepTime)def main(args):m = multiprocessing.Process(target =...
  • 我试图以1 Hz的频率获取数据,所以我在while循环中使用time.sleep(1)来根据需要每秒读取一次数据。为确保我的频率为1 Hz,我正在打印actuel time - the time of the beginning of the script时的值,每个循环似乎都...
  • #输入暂停1秒: ... time.sleep(1) 例2: '''Python 练习实例9 题目:暂停一秒输出。 程序分析:使用 time 模块的 sleep() 函数。''' import time l=[1,2,3,4] for i in range(len(l)): print (l[i]) tim
  • I am having an issue with the time.sleep() function in python. I am running a script that needs to wait for another program to generate txt files. Although, this is a terribly old machine, so when I s...
  • python3.9版本运行以下代码,当注释掉sleep后代码就能正常写入文件,否则文件始终为空是为什么? import time file=open("data.txt","a+") while True: time.sleep(0.1) file.write("test\n") print("add over...
  • I've been toying with the idea of using time.sleep(n) in a python script to make it execute jobs at different intervals. The pseudocode would look like:total_jobs = [...]next_jobs_to_run = next_closes...
  • time.sleep(1) TIME = datetime.datetime.now() print(TIME.strftime("%Y.%m.%d %H-%M-%S")) 输出: 2021.01.14 13-01-03 例2: import time #导入时间模块 #strftime表示按照指定的日期格式返回当前日期: #time ...
  • Yes, I know both are used to wait for some specified time.Selenium:driver.implicitly_wait(10)Python:import timetime.sleep(10)Is there any difference between these two?解决方案time.sleep(secs)time....
  • one.py #!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Liang Xian Sen ...import time from tornado import gen class IndexHandler(tornado.web.RequestHandler): def get(self): self.write('ind
  • 为了让程序可以休眠一定的时间,python中调用time模块的sleep方法实现。 time.sleep(secs)-参数是延迟的时间,以秒为单位。可以是小数,换算成毫秒等单位时间。 >>> import time >>> >>...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 208,954
精华内容 83,581
关键字:

pythontime.sleep

python 订阅