msvcrt — Useful routines from the MS VC++ runtime¶
These functions provide access to some useful capabilities on Windows platforms. Some higher-level modules use these functions to build the Windows implementations of their services. For example, the getpass module uses this in the implementation of the getpass() function.
Further documentation on these functions can be found in the Platform API documentation.
The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use for internationalized applications. The wide char API should be used where ever possible.
Changed in version 3.3: Operations in this module now raise OSError where IOError was raised.
File Operations¶
Lock part of a file based on file descriptor fd from the C runtime. Raises OSError on failure. The locked region of the file extends from the current file position for nbytes bytes, and may continue beyond the end of the file. mode must be one of the LK_* constants listed below. Multiple regions in a file may be locked at the same time, but may not overlap. Adjacent regions are not merged; they must be unlocked individually.
Raises an auditing event msvcrt.locking with arguments fd , mode , nbytes .
msvcrt. LK_LOCK ¶ msvcrt. LK_RLCK ¶
Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, OSError is raised.
msvcrt. LK_NBLCK ¶ msvcrt. LK_NBRLCK ¶
Locks the specified bytes. If the bytes cannot be locked, OSError is raised.
Unlocks the specified bytes, which must have been previously locked.
msvcrt. setmode ( fd , flags ) ¶
Set the line-end translation mode for the file descriptor fd. To set it to text mode, flags should be os.O_TEXT ; for binary, it should be os.O_BINARY .
msvcrt. open_osfhandle ( handle , flags ) ¶
Create a C runtime file descriptor from the file handle handle. The flags parameter should be a bitwise OR of os.O_APPEND , os.O_RDONLY , and os.O_TEXT . The returned file descriptor may be used as a parameter to os.fdopen() to create a file object.
Raises an auditing event msvcrt.open_osfhandle with arguments handle , flags .
msvcrt. get_osfhandle ( fd ) ¶
Return the file handle for the file descriptor fd. Raises OSError if fd is not recognized.
Raises an auditing event msvcrt.get_osfhandle with argument fd .
Console I/O¶
Return True if a keypress is waiting to be read.
Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return ‘\000’ or ‘\xe0’ ; the next call will return the keycode. The Control — C keypress cannot be read with this function.
Wide char variant of getch() , returning a Unicode value.
Similar to getch() , but the keypress will be echoed if it represents a printable character.
Wide char variant of getche() , returning a Unicode value.
msvcrt. putch ( char ) ¶
Print the byte string char to the console without buffering.
msvcrt. putwch ( unicode_char ) ¶
Wide char variant of putch() , accepting a Unicode value.
msvcrt. ungetch ( char ) ¶
Cause the byte string char to be “pushed back” into the console buffer; it will be the next character read by getch() or getche() .
msvcrt. ungetwch ( unicode_char ) ¶
Wide char variant of ungetch() , accepting a Unicode value.
Other Functions¶
Force the malloc() heap to clean itself up and return unused blocks to the operating system. On failure, this raises OSError .
msvcrt — Полезные подпрограммы из среды выполнения MS VC++¶
Данные функции предоставляют доступ к некоторым полезным возможностям на платформах Windows. Некоторые модули более высокого уровня используют данные функции для создания реализации своих служб в Windows. Например, модуль getpass использует его в реализации функции getpass() .
Дополнительную документацию по этим функциям можно найти в документации API платформы.
Модуль реализует как обычный, так и расширенный char варианты консольного API ввода/вывода. Обычный API работает только с ASCII символами и имеет ограниченное применение для интернационализированных приложений. API широких символов следует использовать везде, где это возможно.
Изменено в версии 3.3: Операции в этом модуле теперь вызывают OSError , когда раньше вызывалось IOError .
Файловые операции¶
Блокирует части файла на основе дескриптора файла fd из среды выполнения C. При сбое вызывает OSError . Заблокированная область файла простирается от текущей позиции файла на nbytes байт и может продолжаться до конца файла. mode должен быть одной из констант LK_* , перечисленных ниже. Несколько областей в файле могут быть заблокированы одновременно, но не могут перекрываться. Соседние регионы не объединяются; они должны быть разблокированы по отдельности.
Вызывает событие аудита msvcrt.locking с аргументами fd , mode , nbytes .
msvcrt. LK_LOCK ¶ msvcrt. LK_RLCK ¶
Блокирует указанные байты. Если байты не могут быть заблокированы, программа немедленно повторяет попытку через 1 секунду. Если после 10 попыток байты не могут быть заблокированы, вызывается OSError .
msvcrt. LK_NBLCK ¶ msvcrt. LK_NBRLCK ¶
Блокирует указанные байты. Если байты не могут быть заблокированы, вызывается OSError .
Разблокирует указанные байты, которые должны были быть ранее заблокированы.
Устанавливает режим перевода конца строки для файлового дескриптора fd. Чтобы установить его в текстовый режим, flags должен быть os.O_TEXT ; для двоичного файла это должен быть os.O_BINARY .
msvcrt. open_osfhandle ( handle, flags ) ¶
Создает дескриптор файла среды выполнения C из дескриптора файла handle. Параметр flags должен быть побитовым ИЛИ os.O_APPEND , os.O_RDONLY и os.O_TEXT . Возвращённый файловый дескриптор может использоваться как параметр os.fdopen() для создания файлового объекта.
Вызывает событие аудита msvcrt.open_osfhandle с аргументами handle , flags .
msvcrt. get_osfhandle ( fd ) ¶
Возвращает дескриптор файла для файлового дескриптора fd. Вызывает OSError , если fd не распознан.
Вызывает событие аудита msvcrt.get_osfhandle с аргументом fd .
Консольный ввод/вывод¶
Возвращает True , если нажатие клавиши ожидает чтения.
Читает нажатие клавиши и возвращает полученный символ в виде строки байтов. На консоль ничего не выводится. Данный вызов будет заблокирован, если нажатие клавиши ещё не доступно, но не будет ждать нажатия Enter . Если нажатая клавиша была специальной функциональной клавишей, возвращается ‘\000’ или ‘\xe0’ ; следующий вызов вернёт код ключа. Данная функция не может прочитать нажатие клавиши Control-C .
Широкий символьный вариант getch() , возвращающий Юникод значение.
Аналогична getch() , но нажатие клавиши будет отражено, если оно представляет печатный символ.
Широкий символьный вариант getche() , возвращающий Юникод значение.
msvcrt. putch ( char ) ¶
Выводит строку байтов char на консоль без буферизации.
msvcrt. putwch ( unicode_char ) ¶
Широкий символьный вариант putch() , принимающий Юникод значение.
msvcrt. ungetch ( char ) ¶
Заставляет строку байтов char «оттолкнуть» обратно в буфер консоли; это будет следующий символ, прочитанный getch() или getche() .
msvcrt. ungetwch ( unicode_char ) ¶
Широкий символьный вариант ungetch() , принимающий Юникод значение.
Другие функции¶
Принудительно очищает кучу malloc() и возвращает неиспользуемые блоки в операционную систему. В случае сбоя вызывает OSError .
34.2. msvcrt — Useful routines from the MS VC++ runtime¶
These functions provide access to some useful capabilities on Windows platforms. Some higher-level modules use these functions to build the Windows implementations of their services. For example, the getpass module uses this in the implementation of the getpass() function.
Further documentation on these functions can be found in the Platform API documentation.
The module implements both the normal and wide char variants of the console I/O api. The normal API deals only with ASCII characters and is of limited use for internationalized applications. The wide char API should be used where ever possible.
Changed in version 3.3: Operations in this module now raise OSError where IOError was raised.
34.2.1. File Operations¶
Lock part of a file based on file descriptor fd from the C runtime. Raises OSError on failure. The locked region of the file extends from the current file position for nbytes bytes, and may continue beyond the end of the file. mode must be one of the LK_* constants listed below. Multiple regions in a file may be locked at the same time, but may not overlap. Adjacent regions are not merged; they must be unlocked individually.
msvcrt. LK_LOCK ¶ msvcrt. LK_RLCK ¶
Locks the specified bytes. If the bytes cannot be locked, the program immediately tries again after 1 second. If, after 10 attempts, the bytes cannot be locked, OSError is raised.
msvcrt. LK_NBLCK ¶ msvcrt. LK_NBRLCK ¶
Locks the specified bytes. If the bytes cannot be locked, OSError is raised.
Unlocks the specified bytes, which must have been previously locked.
Set the line-end translation mode for the file descriptor fd. To set it to text mode, flags should be os.O_TEXT ; for binary, it should be os.O_BINARY .
msvcrt. open_osfhandle ( handle, flags ) ¶
Create a C runtime file descriptor from the file handle handle. The flags parameter should be a bitwise OR of os.O_APPEND , os.O_RDONLY , and os.O_TEXT . The returned file descriptor may be used as a parameter to os.fdopen() to create a file object.
msvcrt. get_osfhandle ( fd ) ¶
Return the file handle for the file descriptor fd. Raises OSError if fd is not recognized.
34.2.2. Console I/O¶
Return true if a keypress is waiting to be read.
Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return ‘\000’ or ‘\xe0’ ; the next call will return the keycode. The Control-C keypress cannot be read with this function.
Wide char variant of getch() , returning a Unicode value.
Similar to getch() , but the keypress will be echoed if it represents a printable character.
Wide char variant of getche() , returning a Unicode value.
msvcrt. putch ( char ) ¶
Print the byte string char to the console without buffering.
msvcrt. putwch ( unicode_char ) ¶
Wide char variant of putch() , accepting a Unicode value.
msvcrt. ungetch ( char ) ¶
Cause the byte string char to be “pushed back” into the console buffer; it will be the next character read by getch() or getche() .
msvcrt. ungetwch ( unicode_char ) ¶
Wide char variant of ungetch() , accepting a Unicode value.
34.2.3. Other Functions¶
Force the malloc() heap to clean itself up and return unused blocks to the operating system. On failure, this raises OSError .
Make Python Wait For a Pressed Key
In this article, we will discuss how to pause the execution of Python code until a given key is pressed. This concept can be useful to simply pause Python execution or impose conditions on the code implementation. There are three ways to do this:
- Using keyboard package
- Using msvcrt / getch package
- Using the inbuilt input function
Before discussing those methods, let us discuss a concept we need to understand first.
Prerequisite step
Since we will be reading the key pressed, it is vital that the code editor or IDE we are using to implement these concepts accepts input from the user. I will, therefore, suggest you run the code snippets shown in this article using Visual Studio Code, PowerShell/ Terminal, or JuPyter. If you are running on Sublime Text, install the SublimeRepl package on the editor before running the code (see stackoverflow.com).
Once you are sure that your Python can take input, we can now proceed to discuss the three methods.
Method 1: Using the keyboard package
This package allows us to read the key pressed and then impose our condition at that point. It is not an inbuilt function in Python but can be installed using pip, that is, run pip install keyboard on Windows PowerShell. Once installed, we can execute the following code to learn how this method works:
The above code will keep running until key “q” is pressed, that is when “q” is pressed Python prints “You pressed q” and then the loop is terminated with a “break” keyword.
As an alternative to the above method, we can use the following line of code (In this case, Python waits until the escape key is pressed).
The package also has a function called read_key() that reads the key pressed. You can read more cool things you can do with the keyboard package in its documentation.
In Linux and macOS, you need to have SUDO (Super User DO) privileges to use the keyboard package for executing python code and installing the package.
Method 2: Use msvcrt / getch package
This inbuilt Python package provides useful functions in Microsoft Visual C/C++ Runtime Library (hence the name msvcrt). This article will leverage its functionality of reading the key pressed to pause Python execution.
In the above code snippet, msvcrt.getch() fetches the code pressed in byte format, and therefore we need to use UTF-8 decoding to get it in string format. For example, b’\x0c’ becomes ♀, b’\x1b’ becomes ← (this is the escape key, by the way).
You can input different non-standard characters with the Ctrl key and a letter to see how it works.
The code function introduced in this code snippet is chr(). It returns a string character from an integer (the integer represents the Unicode code point of the string character). Character 27 in the Unicode is an escape character, and therefore pressing the escape key matches chr(27) in the code. Therefore, the while loop is terminated only when the escape key is pressed. It is necessary to use the chr() function only when dealing with problematic decoded characters like escape key; otherwise, when dealing with alphabets, for example, we won’t need chr().
The msvcrt package is only available on Windows OS. On Linux and macOS, the getch package can be used to get the same functionalities as msvcrt. You might need to install the getch package by running pip install getch on the terminal. Once installed, you can now use the code below instead