Как изменить размер cmd python

Python: Get height and the width of console window

Write a Python program to get the height and width of the console window.

Sample Solution:-

Python Code:

def terminal_size(): import fcntl, termios, struct th, tw, hp, wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))) return tw, th print('Number of columns and Rows: ',terminal_size()) 
Number of columns and Rows: (110, 21)

Explanation:

The above Python code defines a function terminal_size() that uses system calls to get the size of the terminal window in columns and rows. It then calls the terminal_size() function and prints the result to the console output.

Then the code imports fcntl, termios, and struct modules.

fcntl — This module performs file control and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines.

termios — This module provides an interface to the POSIX calls for tty I/O control. For a complete description of these calls, see termios(3) Unix manual page.

struct — This module converts between Python values and C structs represented as Python bytes objects. Compact format strings describe the intended conversions to/from Python values.

The terminal_size() function uses the fcntl.ioctl() function to query the size of the terminal window using the termios.TIOCGWINSZ ioctl call. This call returns a struct.pack() object containing four integers representing the number of rows and columns of the terminal, as well as the horizontal and vertical pixel size.

The struct.unpack() function is used to unpack the four integers from the struct.pack() object into separate variables th, tw, hp, and wp. The function then returns the values of tw (the width of the terminal window in columns) and th (the height of the terminal window in rows) as a tuple.

Finally, the print() function is used to print the size of the terminal window to the console.

Flowchart: Get height and the width of console window.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

How to access environment variable values?

Environment variables are accessed through os.environ

import os print(os.environ['HOME'])

Or you can see a list of all the environment variables using:

Читайте также:  Running python code on android

As sometimes you might need to see a complete list!

# using get will return 'None' if a key is not present rather than raise a 'KeyError' print(os.environ.get('KEY_THAT_MIGHT_EXIST')) # os.getenv is equivalent, and can also give a default value instead of `None` print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Python default installation on Windows is C:\Python. If you want to find out while running python you can do:

import sys print(sys.prefix)
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How can I specify the size of the python command line window in my code?

I am making a text adventure and would like the command line window to be a specific size when you run the .py file in the command line window. eg. 300 wide by 250 height. I found a thread on here that shows how to specify the text colour which I also wanted to know. http://www.daniweb.com/forums/post1150939.html#post1150939 Can anybody help? Thanks.

  • 6 Contributors
  • 11 Replies
  • 17K Views
  • 7 Years Discussion Span
  • Latest Post 6 Years Ago Latest Post by DubWine

My advice, run it from IDLE and you get an adjustable output window with a nice background that works across several common platforms.

Thanks for the advice but I’m trying to make my game retro, like the old text based games such as Zork etc. The green text on a black background is classic.

Honestly, get pygame. Its easy to do a text based game with pygame. It will make a screen, and …

import os os.system("mode con cols=50")
os.system("mode con lines=20") #you could also combine them os.system("mode con cols=50 lines=20")

Play around with the numbers until ya find a size you like.
This is windows only.

All 11 Replies

My advice, run it from IDLE and you get an adjustable output window with a nice background that works across several common platforms.

Thanks for the advice but I’m trying to make my game retro, like the old text based games such as Zork etc. The green text on a black background is classic.

Thanks for the advice but I’m trying to make my game retro, like the old text based games such as Zork etc. The green text on a black background is classic.

Honestly, get pygame. Its easy to do a text based game with pygame. It will make a screen, and will update with text. Simple simple things. Make a surface. Fill surface with black.
Make text surface. Write that text to the original surface.
Call for update, and repeat.

Читайте также:  Python remote desktop github

Источник

Как задать размер окна консоли (Windows)?

Хочу что-бы при запуске кода в консоли, окно консоли принимало статичный указанный размер в количестве символов, например 100х50.

Как задать фиксированный размер консоли для приложения?
Объясните, почему пользуясь методом Console.SetWindowSize (Int32, Int32) — окно уменьшается, но.

Как зафиксировать размер окна в консоли ?
По иксам вроде зафиксирован, а игрик стягивается =( может какие то стили есть окна консоли ? .

Как задать максимальный размер окна в режиме Maximized
Есть форма, сайзабле, без кэпшена и контролБокса. На максимизирование реагирует не так как.

Как задать размер стороннего окна при открытии и расположение от формы (справа/слева)?
Подскажите! Открываю некий скрипт в программе. Команду подаю из делфи и собственно открываю этот.

Эксперт по компьютерным сетям

Эксперт Python

ЦитатаСообщение от bdsmback13 Посмотреть сообщение

Только на вашем компьютере? Тогда ответ уже дан выше.

Если это необходимо на любых компьютерах с windows, где будет запускаться ваш код, тогда самый элементарный способ — через внутреннюю команду cmd:

os.system("mode con cols=100 lines=50")

Но она задает размер буфера экрана консоли и автоматически увеличивает и размер самого окна до указанного числа строк и колонок.

Более тонкая настройка получится через API функции консоли: SetWindowPos и SetConsoleScreenBufferSize.

P.S. Определитесь, что именно вам нужно: размер буфера экрана — он задается в символах (колонках\строках) посредством SetConsoleScreenBufferSize.
Или размер окна консоли — он задается пикселях посредством SetWindowPos.

Задать размер консоли при запуске
Здравствуйте,подскажите как можно задать размер консоли в паскаль ABC .NET. Сделал программу с.

VS 2017, C#, Задать положение окна консоли
Всем привет! Консольное приложение. Окно консоли нужно разместить на экране в заданном месте.

Как задать единый размер для всех папок в Windows XP?
Добрый день, дорогие форумчане, у меня есть один вопрос — как задать единый размер для всех папок в.

Как в System.Windows.Forms задать форме фиксированный размер?
Как сделать так, чтобы пользователь не мог изменять форму написанную на System.Windows.Forms.

CEFSharp размер окна консоли разработчика
Приветы. Вопрос знатокам. Есть CEFSharp (v45 — надо чтобы на XP запускалось) При запуске.

Размер окна консоли (осталось доделать)
Прошу переделать эту консольную прогу. Чтобы она выводила не сетевые приложения, а размер окна.

Источник

Python Programmatically Change Console font size

I found the code below which is supposed to programmatically change the console font size. I’m on Windows 10. However, whatever values I tweak, I can’t seem to get any control over the font size, and also for some reason the console which gets opened when I run this script is very wide. I have no idea how ctypes works — all I want is to modify the size of the console font from inside Python. Any actual working solutions?

import ctypes LF_FACESIZE = 32 STD_OUTPUT_HANDLE = -11 class COORD(ctypes.Structure): _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)] class CONSOLE_FONT_INFOEX(ctypes.Structure): _fields_ = [("cbSize", ctypes.c_ulong), ("nFont", ctypes.c_ulong), ("dwFontSize", COORD), ("FontFamily", ctypes.c_uint), ("FontWeight", ctypes.c_uint), ("FaceName", ctypes.c_wchar * LF_FACESIZE)] font = CONSOLE_FONT_INFOEX() font.cbSize = ctypes.sizeof(CONSOLE_FONT_INFOEX) font.nFont = 12 font.dwFontSize.X = 11 font.dwFontSize.Y = 18 font.FontFamily = 54 font.FontWeight = 400 font.FaceName = "Lucida Console" handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) ctypes.windll.kernel32.SetCurrentConsoleFontEx( handle, ctypes.c_long(False), ctypes.pointer(font)) print("Foo") 

3 Answers 3

Before everything, check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati’s answer) for a common pitfall when working with CTypes (calling functions).

Читайте также:  Установить pip python debian

I changed your code «a bit».

#!/usr/bin/env python import ctypes as cts import ctypes.wintypes as wts import sys LF_FACESIZE = 32 STD_OUTPUT_HANDLE = -11 class CONSOLE_FONT_INFOEX(cts.Structure): _fields_ = ( ("cbSize", wts.ULONG), ("nFont", wts.DWORD), ("dwFontSize", wts._COORD), ("FontFamily", wts.UINT), ("FontWeight", wts.UINT), ("FaceName", wts.WCHAR * LF_FACESIZE) ) def main(*argv): kernel32 = cts.WinDLL("Kernel32.dll") GetLastError = kernel32.GetLastError GetLastError.argtypes = () GetLastError.restype = wts.DWORD GetStdHandle = kernel32.GetStdHandle GetStdHandle.argtypes = (wts.DWORD,) GetStdHandle.restype = wts.HANDLE GetCurrentConsoleFontEx = kernel32.GetCurrentConsoleFontEx GetCurrentConsoleFontEx.argtypes = (wts.HANDLE, wts.BOOL, cts.POINTER(CONSOLE_FONT_INFOEX)) GetCurrentConsoleFontEx.restype = wts.BOOL SetCurrentConsoleFontEx = kernel32.SetCurrentConsoleFontEx SetCurrentConsoleFontEx.argtypes = (wts.HANDLE, wts.BOOL, cts.POINTER(CONSOLE_FONT_INFOEX)) SetCurrentConsoleFontEx.restype = wts.BOOL # Get stdout handle stdout = GetStdHandle(STD_OUTPUT_HANDLE) if not stdout: print(" error: ".format(GetStdHandle.__name__, GetLastError())) return # Get current font characteristics font = CONSOLE_FONT_INFOEX() font.cbSize = cts.sizeof(CONSOLE_FONT_INFOEX) res = GetCurrentConsoleFontEx(stdout, False, cts.byref(font)) if not res: print(" error: ".format(GetCurrentConsoleFontEx.__name__, GetLastError())) return # Display font information print("Console information for ".format(font)) for field_name, _ in font._fields_: field_data = getattr(font, field_name) if field_name == "dwFontSize": print(" : <>".format(field_name, field_data.X, field_data.Y)) else: print(" : ".format(field_name, field_data)) while 1: try: height = int(input("\nEnter font height (invalid to exit): ")) except: break # Alter font height font.dwFontSize.X = 10 # Changing X has no effect (at least on my machine) font.dwFontSize.Y = height # Display font information res = SetCurrentConsoleFontEx(stdout, False, cts.byref(font)) if not res: print(" error: ".format(SetCurrentConsoleFontEx.__name__, GetLastError())) return print("OMG! The window changed :)") # Get current font characteristics again res = GetCurrentConsoleFontEx(stdout, False, cts.byref(font)) if not res: print(" error: ".format(GetCurrentConsoleFontEx.__name__, GetLastError())) return print("\nNew sizes X: , Y: ".format(font.dwFontSize.X, font.dwFontSize.Y)) if __name__ == "__main__": print("Python bit on \n".format(" ".join(elem.strip() for elem in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform)) rc = main(*sys.argv[1:]) print("\nDone.\n") sys.exit(rc) 
  • CTypes allows low level access similar to C (only the syntax is Python)
  • Code uses [MS.Learn]: SetConsoleTextAttribute function
    • In order to avoid setting invalid values, it’s used in conjunction with its counterpart: [MS.Learn]: GetCurrentConsoleFontEx function. Call that function in order to populate the CONSOLE_FONT_INFOEX structure, then modify only the desired values
    • There are «simpler» functions (e.g. [MS.Learn]: GetCurrentConsoleFont function or [MS.Learn]: GetConsoleFontSize function), but unfortunately there are no corresponding setters
    • Note that all referenced WinAPI functions are deprecated

    Источник

Оцените статью