Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
#Andijan
Over the past 10 days, shepherds have brought a herd of horses and sheep onto the lands of the “Green View” farm, destroying years of tree seedlings grown on the hills of Asaka District, Andijan region. In addition, the drip irrigation systems were damaged and rendered unusable.
The farmers repeatedly warned the shepherds, recorded the situation on video, and appealed to the internal affairs authorities, but no action was taken. As a result, the shepherds continue to graze their animals on the farm’s land.
The farmer suffered from back pain for more than a week and, after recording the damage on video and contacting the 102 hotline, still received no response or action from the authorities.
The farmers ask:
Why is their labor not protected?
Why is there no accountability for violations of the law?
Who protects the work done to turn desert lands into green areas?
They request that the Ministry of Internal Affairs of the Republic of Uzbekistan pay attention to this situation and ensure justice is served within the framework of the law. ☘️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.
#Andijan The treatment of birds by staff at the Andijan Zoo has raised serious concerns. This raises an important question: do we need private zoos?
The greatest risk is cruelty towards animals. In many cases, the pursuit of profit is placed above the peace and well-being of animals.
☘️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.
❓ Ingliz tilida e’tiroz bildirishingiz kerak…
Lekin qo‘pol chiqib qolishni xohlamaysiz? 👀
Bugungi mini-viktorinada aynan shuni mashq qilamiz!
Qaysi variant madaniyatli va to‘g‘ri?👇
🅰️ I’m not agreeing with that
🅱️ I beg to differ
🆑 I don’t think so, and you’re wrong
💬 Javobingizni kommentariyada yozing!
To‘g‘ri javob va tushuntirish — videoda! 🎥
📌 Boshqa foydali iboralarni o‘rganmoqchimisiz? Obuna bo‘ling va bizni kuzatib boring!
📞 Aloqa uchun:
📱 +998742261078 / +998994314134
📨 Telegram: @admofadc
#adcenglish#ingliztili#englishquiz#andijan
Senga yana nima yetmaydi?
Xattoki,baxt yelib-tolmoqlik.
Hammaga ham nasib etmaydi,
Tongda turib,nafas olmoqlik...
#spring#nature#Andijan#pomegranate_flowers
@madinaazam
🇺🇿Поздравляем всех вас с одним из главных праздников нашей страны – «8 декабря — День Конституции Республики Узбекистан».
Желаем всем Вам и Вашим близким крепкого здоровья, семейного благополучия, успехов в Вашей профессиональной деятельности и удачи во всех благих начинаниях!
#adceducate#adc#andijan#tashkent#taraqqiyot#instagood#instagram#asaka#uzbekistan#adcteam#andijandevelopmentcenter#privateschool#спраздником#holiday
Telegram Instagram FacebookTikTokYoutube