May 2001
Intermediate to advanced
304 pages
6h 12m
English
(Windows/DOS only) The msvcrt module gives you access to a number of
functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT).
Example 12-13 demonstrates the getch function reading a single keypress from
the console.
Example 12-13. Using the msvcrt Module to Get Key Presses
File: msvcrt-example-1.py
import msvcrt
print "press 'escape' to quit..."
while 1:
char = msvcrt.getch()
if char == chr(27):
break
print char,
if char == chr(13):
print
press 'escape' to quit...
h e l l o
The kbhit function returns true if a key has been
pressed (which means that getch won’t block), as shown in Example 12-14.
Example 12-14. Using the msvcrt Module to Poll the Keyboard
File: msvcrt-example-2.py
import msvcrt
import time
print "press SPACE to enter the serial number"
while not msvcrt.kbhit() or msvcrt.getch() != " ":
# do something else
print ".",
time.sleep(0.1)
print
# clear the keyboard buffer
while msvcrt.kbhit():
msvcrt.getch()
serial = raw_input("enter your serial number: ")
print "serial number is", serial
press SPACE to enter the serial number
. . . . . . . . . . . . . . . . . . . . . . . .
enter your serial number: 10
serial number is 10The locking function in Example 12-15 can be used to implement
cross-process file locking under Windows.
Example 12-15. Using the msvcrt Module for File Locking
File: msvcrt-example-3.py import msvcrt import os LK_UNLCK = 0 # unlock the file region LK_LOCK = 1 # lock the file region LK_NBLCK = 2 # non-blocking lock LK_RLCK = 3 ...
Read now
Unlock full access