Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
🔥✨Unleash the Power of Aston Martin Valiant!✨🔥
Embark on a journey of power and precision with the Aston Martin Valiant, driven by a formidable 5.2-liter V12 engine with twin turbocharging, delivering an impressive 745 horsepower (compared to 715 in the Valour). Feel the exhilarating torque of 753 Nm propelling you forward with each twist of the throttle. Get ready to ignite your senses!
This fusion of power and performance is harnessed by an exclusive six-speed manual transmission, seamlessly transferring power to the rear wheels, creating an unmatched driving experience. Trust the Aston Martin Valiant to experience the exceptional blend of technology and emotion on the road.
Dive into the true embodiment of power, style, and automotive mastery with the Aston Martin Valiant!
#AstonMartin#Valiant#V12Power#Performance#DrivingExperience
🚗✨Introducing the Speedster 612 TR Teppista!✨🚗
This stunning masterpiece, based on the iconic Ferrari 250 Testarossa from 1957, is now available in the UAE for an astonishing 823 million rubles! 💰🇦🇪
🔍What makes it so special?
- Crafted in 2008 with a sleek carbon body that’s longer and wider than ever! 🖤
- Powered by a roaring V12 engine with a capacity of 5.7 liters! 🏎️💨
A true collector’s dream! 🌟
#Speedster612TR#Ferrari#LuxuryCars#CarCollector#UAE#AutomotiveArt#V12Power#Auto
✨ Introducing the Rolls-Royce Ghost Series II ✨
The updated sedan features a stunning new headlight design and an enlarged grille, reminiscent of the Spectre coupe! 🚗💎 The 22-inch wheels showcase fresh patterns, and a new deep blue shade joins the color palette. 🎨🔵
Inside, experience luxury with a unique bamboo-based fabric, crafted over a year! 🌿🛋️ The media system now operates on the advanced Spirit OS. 📱🎶
Under the hood, the powerful turbocharged V12 engine boasts 563 hp (591 hp in the Black Badge version) and is paired with an 8-speed automatic transmission for smooth rear-wheel drive. 💨⚙️
Elevate your journey with the Ghost Series II! 🌌
#RollsRoyce#GhostSeriesII#Luxury#AutomotiveExcellence#V12Power#Bespoke#EleganceOnWheels#Auto