Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
🌍 In some places, coastal cliffs are vanishing so quickly that entire villages have moved inland within a single generation, as sea level rise and stronger storms speed up the erosion. ✨
#erosion⚡#coastlines⚡#climate⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The boundary where the Earth's solid land meets the sea—called the coastline—is constantly changing. Waves, tides, and storms reshape these edges every day, making coastlines dynamic and ever-shifting. ✨
#geography⚡#coastlines⚡#change⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Coastal erosion is eating away cliffs and beaches so fast in some places that detailed maps need updating every year, with new shorelines appearing and disappearing before our eyes. ✨
#coastlines⚡#erosion⚡#mapping⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Coastal erosion now removes up to 24 square meters of land per meter of shoreline in some parts of West Africa each year, forcing whole fishing villages to move further inland. ✨
#coastlines⚡#erosion⚡#sea-level ⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Satellite data shows that some coastlines have retreated by over 50 meters in just a decade, as rising sea levels and stronger storms rapidly reshape shores across the globe. ✨
#erosion⚡#sea-level ⚡#coastlines⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Mediterranean coastline holds more than 150 million-year-old fossils, often exposed in seaside cliffs by constant wave erosion. Some beach rocks here contain ancient traces of life dating back to the dinosaurs. ✨
#coastlines⚡#fossils⚡#erosion⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Mangroves protect coastlines from storms and rising seas, but over a third have been lost worldwide. Their destruction leaves many regions more vulnerable to flooding and erosion. ✨
#mangroves⚡#coastlines⚡#erosion⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Salar de Uyuni in Bolivia holds an ancient, dried-up sea that now forms the world's largest salt flat. Rare rainy seasons briefly transform it into a mirror reflecting the entire sky. ✨
#coastlines⚡#saltflat⚡#landscape⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Bohai Sea in China is so shallow that its average depth is just 18 meters—less than a six-story building. This makes it one of the least deep seas in the world’s coastal regions. ✨
#seas⚡#coastlines⚡#shallow⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels