Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

Chris Angelico rosuav at gmail.com
Wed Jun 18 19:38:14 EDT 2014


On Thu, Jun 19, 2014 at 1:24 AM, crow <wentlv at gmail.com> wrote:
> Here is a sample code that can reproduce this issue, you need to wait for it to run for a while.
> ******************
> import time
> import threading
> import wx
>
> def sleep():
>     while True:
>         t = time.time()
>         time.sleep(1)
>         print "Actually sleep:", time.time() - t
>
>
> t1 = threading.Thread(target=sleep)
> t1.start()
>
> app =wx.App(False)
> frame = wx.Frame(None, title="test")
> frame.Show(True)
> app.MainLoop()

Okay... you're adding two important complications that you hadn't
mentioned originally: Python threads, and a GUI main loop. I could
explain the impact that each of these might have on time.sleep(), but
given your other recent questions, I'm going to say this instead:

Don't be afraid of the console.

When you write Python code, start by assuming that it will be run in
the standard "glass teletype" console. One thread, simple imperative
code, no GUI event loop, keep it simple. Later on, you can add fancy
features, but start by getting your main program code working in a
simpler environment.

In a lot of cases, a simple single-threaded console program is
actually all you need. You can transport that to other environments
easily (maybe run it under a web framework with minimal changes), and
it'll run perfectly on pretty much any build of Python, without any
fiddling around. And you spend so little time and code on your UI that
way; any half-decently-usable GUI will probably take you a good bit of
effort to code, but a good console UI just requires this:

something = raw_input("Enter something: ")
print("Result: "+result)

(Or, better: Upgrade to Python 3, and drop the "raw_" prefix. You get
other benefits too.)

Play with GUIs later, if at all. Start by getting the guts of your code right.

ChrisA



More information about the Python-list mailing list