【问题标题】:What Python Module Should I Use For Updating?我应该使用什么 Python 模块进行更新?
【发布时间】:2011-01-13 16:32:21
【问题描述】:

好吧,我已经将 time 模块用于 time.sleep(x) 函数有一段时间了……但我需要一些不会暂停 shell 的东西,这样用户就可以在程序计数时继续使用程序。

为了更“具体”,假设我有一个程序需要等待 5 秒才能执行一个函数。在这个使用 time.sleep() 函数的时候,用户不能在 shell 中输入任何东西,因为它正在睡觉。但是,当用户能够使用 shell 时,我需要 Python 在后台“计算 5 秒”。这可能吗?

【问题讨论】:

标签: python module


【解决方案1】:

threading ?您应该在一个工人和另一个单独的工人中处理您的工作,在那里您可以计算或与时间一起睡觉。睡眠

这是一个示例,可以帮助您理解和使用 time.sleep 中的线程

import threading
import time

def sleeper():
    print 'Starting to sleep'
    time.sleep(10)
    print 'Just waking up..'
    print 'snooze'
    print 'oh no. I have to get up.'

def worker():
    print 'Starting to work'
    time.sleep(1) # this also a work. :)
    print 'Done with Work'

t = threading.Thread(name='sleeper', target=sleeper)
w = threading.Thread(name='worker', target=worker)

w.start()
t.start()

【讨论】:

  • 好的,在我接受你的回答之前......我还需要知道一件事......我正在查看线程模块的示例,并尝试使用这个:def hello(): print "hello, world" t = Timer(30.0, hello) t.start() # 30 秒后,将打印“hello, world” 但这不起作用,因为它找不到子类计时器模块。关于为什么的任何想法?
  • 我为您添加了一个易于理解的示例。 :) 是的 Timer 也可以用于类似的效果。 Timer 是线程的子类,可以直接实现延迟并行执行。谢谢。
猜你喜欢
  • 2015-02-27
  • 2019-03-09
  • 2013-06-02
  • 1970-01-01
  • 2010-11-30
  • 2013-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多