Архив за день: 2020-06-06

Python: чтение нажатия кнопок в консоли Windows

import msvcrt
msvcrt.getch()
b’f’
msvcrt.getch()
b’\xe0′
msvcrt.getch()
b’M’
msvcrt.getch()
b’\xe0′
msvcrt.getch()
b’H’
msvcrt.getch()
b’\r’
for i in range(0,5):
… msvcrt.getch()

b’1′
b’f’
b’5′
b’\r’
b’\xe0′

Шпаргалка по типам данных в Python

Text Type: str
Numeric Types: int, float, complex
Sequence Types: list(список), tuple(кортеж), range
Mapping Type: dict(словарь)
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list(список)
x = ("apple", "banana", "cherry") tuple(кортеж)
x = range(6) range
x = {"name" : "John", "age" : 36} dict(словарь)
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

Python: как узнать размер окна терминала консоли в Windows и Linux

Windows

Найдено здесь: https://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

from ctypes import windll, create_string_buffer

# stdin handle is -10
# stdout handle is -11
# stderr handle is -12

h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

if res:
    import struct
    (bufx, bufy, curx, cury, wattr,
     left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    sizex = right - left + 1
    sizey = bottom - top + 1
else:
    sizex, sizey = 80, 25 # can't determine actual size - return default values

print sizex, sizey

Проверил, работает

Linux

>>> import os
>>> os.get_terminal_size()
os.terminal_size(columns=80, lines=24)
>>> os.get_terminal_size().columns
80
>>> os.get_terminal_size().lines
24
>>>