Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
🌟Thinking of applying for the IRAS scholarship?
Get insider tips from our current scholars to help with your application. ✍️ Don’t miss this opportunity to contribute meaningfully to Singapore’s economic and social growth. Apply to be an IRAS scholar at go.gov.sg/scholarapply by 31 March 2026.
#IRASscholarships#scholarships
Where tax builds tomorrow. 🇸🇬
Our scholars Nathaniel, Jing Rong, and Yern-Wei share about their journey in IRAS and how their work drives Singapore’s economic growth and inclusive society. Join us and discover diverse, purpose-driven careers that foster dynamic learning and collaborative innovation!
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
✍️ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where every expertise matters. 💼
At IRAS, we bring together different disciplines and unique specialists to work on projects that drives Singapore’s economic growth. IRAS scholarships are open to students from diverse areas of study.
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where tax builds tomorrow.💡
With pre-filled forms containing income details and tax reliefs, filing taxes is done in a matter of minutes. But what goes on behind-the-scenes to create this smooth taxpaying experience? Meet IRAS Director Leong Shi Wei, who leads multidisciplinary teams that oversee data policy, governance, and digital partnerships - making paying taxes a seamless and automated experience. Learn more about his work at IRAS here: https://go.gov.sg/iras-designing-the-tax-experience
Ready to collaborate with diverse teams on projects of national importance? 🇸🇬Apply to be an IRAS scholar today at go.gov.sg/scholarapply. Applications close on 31 Mar 2026.
#IRASscholarships#scholarships
Where every expertise matters.🧪
At IRAS, we bring together diverse and unique disciplines and specialists to drive projects that shape Singapore’s future. Meet Charmaine Tan, an IRAS scholar pursuing her Bachelor of Science in Life Sciences and Minor in Forensic Science, as she shares how her academic passion translates into meaningful impact.
Ready to put your expertise towards nation-building? 🌟 Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where growth knows no limits. 🌱
What does it mean to be an IRAS scholar? Meet Shaine Goh (Software Engineer, Infocomm Division) whose journey with the IRAS Merit Undergraduate Scholarship turned her potential into real-world impact. 💼 From computing skills to transforming tax services, Shaine shows how innovation can reshape the taxpayer experience. Read her story: go.gov.sg/iras-shaine-goh
At IRAS, we invest in your personal growth so you can maximise your full potential. Ready to grow without limits? ✨ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#scholarships#IRASscholarships
Where tax builds tomorrow.
IRAS scholarships are your gateway to a meaningful career that propels Singapore’s economic growth forward. Take your first step with us and unlock endless possibilities.
Ready to shape tomorrow? Learn more about life at IRAS at go.gov.sg/lifeatiras and visit go.gov.sg/scholarapply to apply to be an IRAS scholar via BrightSparks today.
#scholarships#IRASscholarships
🌐 As a Tax Director in IRAS’ Corporate Tax Division, IRAS scholar Joanne Tan refines tax laws and shapes policies that strengthen Singapore’s economic future, while leading a team of officers to discover the dynamic side of tax work. Learn more about her journey at IRAS here.
Apply for IRAS scholarships today at go.gov.sg/scholarapply
#lifeatIRAS#IRASscholarships#scholarships
Have questions about IRAS Scholarships? We’re here to answer them. 💬
Our scholarship application is now open, so don’t miss out! Apply today at go.gov.sg/scholarapply.
For more details, feel free to reach out to us at [email protected].
#IRASscholarships#scholarship#lifeatiras
📢 Calling all A-level/IB graduates and university students from all disciplines!
Catch a glimpse of life as an IRAS intern – follow our scholar Gerald Wong through his #dayinthelife.
Ready to make a difference? Join our future-ready #IRASFam and do work that matters in a collaborative, empowering environment. 🚀 Apply for IRAS scholarships at go.gov.sg/scholarapply or internships at www.careers.gov.sg today.
#lifeatIRAS#IRASscholarships