Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль code.
Как это может пригодиться?
🔸 Вам не хватает pdb и хочется больше "власти"
🔸 Нужно запросить у юзера данные в достаточно сложном виде. В этом случае можно попросить его создать что ему надо и сохранить в определённую переменную, с которой потом и работать.
🔸 Нужна изолированная среда для выполнения каких-либо действий.
🔸 Просто забавы ради😁
Запускается консоль очень просто
import code
ic = code.InteractiveConsole()
try:
ic.interact()
except SystemExit:
pass
Выход обратно на предыдущий уровень происходит как обычно, вызов функции exit() или клавиши Ctrl+D(Ctrl+Z для Windows).
Я набросал простой пример с некоторым функционалом
🔹 Меняются символы приглашения
🔹 В неймспейсы добавляются дополнительные объекты
🔹 Считается время, проведённое в интерактивном режиме
🔹 Скрипт просит юзера заполнить переменную и по выходу распечатывает её значение
Код здесь ↗️
Для запуска сохраните код в файл и запускайте как обычный скрипт.
python my_console.py
Для быстрого запуска можно сделать отдельный алиас
alias py="python3 /home/username/my_console.py"
#tricks#source
#RedBook🌷 Tulipa affinis (Relative Tulip)
A rare endemic plant of the Western Pamir-Alay region, found only in limited areas. Its bright red flower with a black center and yellow border makes the plant especially striking — but this beauty is also one of the reasons it is often destroyed.
📍Distribution
In Uzbekistan, it grows in the Jizzakh, Samarkand, and Navoi regions — on the Turkestan and Malguzar mountain ranges and in the Nurata Mountains. It is also found in Kyrgyzstan and Tajikistan. The plant grows on rocky slopes, in gorges, and among shrubs and juniper woodlands.
🌱Plant characteristics
▫️ Perennial bulbous plant, 15–25 cm tall
▫️ Blooms in April–May
▫️ Reproduces by seeds and vegetatively
▫️ Occurs rarely in nature — as single plants or small groups
⚠️Why the species is under threat
The main reasons for the population decline are mass collection of flowers and livestock grazing, which destroy the plant’s natural habitat.
🌿Conservation status
The plant has been cultivated in the Botanical Garden of the Academy of Sciences of the Republic of Uzbekistan since 1957 and is protected in Zaamin State Reserve and Nurata State Reserve.
💚 Protecting rare plants is an important part of preserving biodiversity. Take care of nature and do not pick wild flowers. ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
📕#RedBook WILD GRAPEVINE
Latin name: Vitis vinifera L.
Status: Category 3 – Rare species with a fragmented range in Uzbekistan
🌿 Description
A climbing woody vine reaching up to 30 meters in length.
Leaves are simple, nearly round, 3–5-lobed or palmately divided, with a heart-shaped base; edges are serrated or crenate.
The inflorescence is a dense or loose panicle.
Fruits vary in color and shape.
Flowers in May–June, fruits ripen in July–October.
📍 Distribution
In Uzbekistan:
– Jizzakh, Surkhandarya, Tashkent regions:
▪️ Nurata range (Gurdara and Bolosoy gorges)
▪️ Gissar range (Sangardak and Tupalang river basins)
– Western Tien Shan: Pskem, Ugam, Korzhantau, Chatkal ranges
Also found in:
– Tajikistan
– Kyrgyzstan
– Kazakhstan
🌱 Habitat
Grows along riverbanks, in gorges, on gravelly and fine-soil mountain slopes.
🔢 Population
Occurs as solitary plants or in small clusters.
♻️ Reproduction
Reproduces by seeds and vegetatively.
⚠️ Threats and Causes of Decline
– Trampling and damage caused by grazing livestock
– Use of the plant as firewood
These factors lead to a steady reduction in population and habitat range.
🌿 Domestication and Importance
Cultivated in all botanical gardens of Central Asia, in specialized horticultural research plots, and at breeding stations for developing new varieties.
🛡 Conservation Measures
– Protected in the Nurata and Chatkal State Nature Reserves
– Under protection in the Ugam–Chatkal National Park ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
🦅 Peregrine Falcon — the fastest bird in the world
The peregrine falcon can reach speeds of up to 390 km/h during a dive. These majestic predators hunt birds and small mammals, playing a vital role in maintaining the balance of ecosystems.
❗️ Important: the peregrine falcon is listed in the Red Book of Uzbekistan. Its population is under threat due to habitat destruction, poaching, and environmental pollution.
🌿 Protecting peregrine falcons is a contribution to preserving the biodiversity and future of our country’s nature.
#PeregrineFalcon#RedBook#ProtectNature#RareBirds#Biodiversity
☘️ Follow the latest environmental news on @ekologuz. Subscribe and send your suggestions and feedback via @eklguz_bot