How can I make a program wait for a few seconds before proceeding? An example of where this would come in handy is when the program allows the user 5 seconds before it proceeds with some default option... can I do this using python?

Recommended Answers

All 9 Replies

>>> import time
>>> dir(time)
['__doc__',
 '__name__',
 '__package__',
 'accept2dyear',
 'altzone',
 'asctime',
 'clock',
 'ctime',
 'daylight',
 'gmtime',
 'localtime',
 'mktime',
 'sleep',
 'strftime',
 'strptime',
 'struct_time',
 'time',
 'timezone',
 'tzname']
>>> help(time.sleep)
Help on built-in function sleep in module time:

sleep(...)
    sleep(seconds)
    
    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.

>>>

Thanks... that's what I needed. However, I'd like to know HOW a timer is created in python.

Thanks... that's what I needed. However, I'd like to know HOW a timer is created in python.

Apart from the sleep function, there is a Timer class in the threading module and there are timers in gui modules like tkinter and wxpython. Other ways to wait are the threading.Condition.wait() function, socket reading with a timeout and functions like select.select which wait for I/O with an optional timeout.
Your choice depends on what you want to do exactly.

You can also keep a program busy with a for loop, but the exact delay will depend on your computer's capabilities.

Apart from the sleep function, there is a Timer class in the threading module and there are timers in gui modules like tkinter and wxpython. Other ways to wait are the threading.Condition.wait() function, socket reading with a timeout and functions like select.select which wait for I/O with an optional timeout.
Your choice depends on what you want to do exactly.

What I meant was 'how does python keep track of the passing seconds'? Does it count the clock pulses or something like that?

As far as I understand, module time and most timers use the hardware timer (internal clock chip). Using a float representing UTC time in seconds since the epoch created by the chip. The epoch on most of those chips is 1/1/1970 00:00:00

You can see seconds since epoch with this little Python program ...

import time

print(time.time())

This value is updated 18.2 times per second.

Looking into pyton 2.6 source code (timemodule.c) we find this implementation of sleep

/* Implement floatsleep() for various platforms.
   When interrupted (or when another error occurs), return -1 and
   set an exception; else return 0. */

static int
floatsleep(double secs)
{
/* XXX Should test for MS_WINDOWS first! */
#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
	struct timeval t;
	double frac;
	frac = fmod(secs, 1.0);
	secs = floor(secs);
	t.tv_sec = (long)secs;
	t.tv_usec = (long)(frac*1000000.0);
	Py_BEGIN_ALLOW_THREADS
	if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
#ifdef EINTR
		if (errno != EINTR) {
#else
		if (1) {
#endif
			Py_BLOCK_THREADS
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
	}
	Py_END_ALLOW_THREADS
#elif defined(__WATCOMC__) && !defined(__QNX__)
	/* XXX Can't interrupt this sleep */
	Py_BEGIN_ALLOW_THREADS
	delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
	Py_END_ALLOW_THREADS
#elif defined(MS_WINDOWS)
	{
		double millisecs = secs * 1000.0;
		unsigned long ul_millis;

		if (millisecs > (double)ULONG_MAX) {
			PyErr_SetString(PyExc_OverflowError,
					"sleep length is too large");
			return -1;
		}
		Py_BEGIN_ALLOW_THREADS
		/* Allow sleep(0) to maintain win32 semantics, and as decreed
		 * by Guido, only the main thread can be interrupted.
		 */
		ul_millis = (unsigned long)millisecs;
		if (ul_millis == 0 ||
		    main_thread != PyThread_get_thread_ident())
			Sleep(ul_millis);
		else {
			DWORD rc;
			ResetEvent(hInterruptEvent);
			rc = WaitForSingleObject(hInterruptEvent, ul_millis);
			if (rc == WAIT_OBJECT_0) {
				/* Yield to make sure real Python signal
				 * handler called.
				 */
				Sleep(1);
				Py_BLOCK_THREADS
				errno = EINTR;
				PyErr_SetFromErrno(PyExc_IOError);
				return -1;
			}
		}
		Py_END_ALLOW_THREADS
	}
#elif defined(PYOS_OS2)
	/* This Sleep *IS* Interruptable by Exceptions */
	Py_BEGIN_ALLOW_THREADS
	if (DosSleep(secs * 1000) != NO_ERROR) {
		Py_BLOCK_THREADS
		PyErr_SetFromErrno(PyExc_IOError);
		return -1;
	}
	Py_END_ALLOW_THREADS
#elif defined(__BEOS__)
	/* This sleep *CAN BE* interrupted. */
	{
		if( secs <= 0.0 ) {
			return;
		}

		Py_BEGIN_ALLOW_THREADS
		/* BeOS snooze() is in microseconds... */
		if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
			Py_BLOCK_THREADS
			PyErr_SetFromErrno( PyExc_IOError );
			return -1;
		}
		Py_END_ALLOW_THREADS
	}
#elif defined(RISCOS)
	if (secs <= 0.0)
		return 0;
	Py_BEGIN_ALLOW_THREADS
	/* This sleep *CAN BE* interrupted. */
	if ( riscos_sleep(secs) )
		return -1;
	Py_END_ALLOW_THREADS
#elif defined(PLAN9)
	{
		double millisecs = secs * 1000.0;
		if (millisecs > (double)LONG_MAX) {
			PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
			return -1;
		}
		/* This sleep *CAN BE* interrupted. */
		Py_BEGIN_ALLOW_THREADS
		if(sleep((long)millisecs) < 0){
			Py_BLOCK_THREADS
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
		Py_END_ALLOW_THREADS
	}
#else
	/* XXX Can't interrupt this sleep */
	Py_BEGIN_ALLOW_THREADS
	sleep((int)secs);
	Py_END_ALLOW_THREADS
#endif

	return 0;
}

The code is OS dependent. For linux, you see that the sleep is implemented by calling select(0,0,0,0, &t) , so your question is now to find the implementation of the C function select. On other OSes, there seem to be a system Sleep or DosSleep function, and you should look for their implementations with the help of our good friend GOOGLE.

Oh dear.. I think I'll leave it at that... ;-) Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.