Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
🎉🇿🇦 Happy Freedom Day, South Africa!
Today, 27 April, South Africa celebrates the 31st anniversary of its first democratic elections — a landmark event that marked the beginning of a new era of freedom, equality and justice.
Held in 1994, these historic elections were the first in which citizens of all races could exercise their right to vote, putting an end to decades of apartheid rule.
Freedom Day honours the sacrifices and courage of those who fought tirelessly against injustice and discrimination, paving the way for a democratic and inclusive South Africa.
The Consulate General of the Russian Federation in Cape Town extends its warmest congratulations to all South Africans on this significant occasion!
#FreedomDay#SouthAfrica
🇿🇦Freedom Day is a South African public holiday celebrated on April 27. 🎉
It commemorates the first democratic post-apartheid non-racial elections held on April 27, 1994, which led to the election of Nelson Mandela as President. 🇿🇦✨
These elections were the first where every South African citizen over the age of 18—including foreign residents—could vote.
📅 Freedom Day marks the end of colonialism and apartheid in South Africa.
🎥 Watch the video with English text:
https://www.youtube.com/watch?v=6OKB8EoVqWc
#History#Culture#Holidays#FreedomDay#Apartheid#SouthAfrica
Sydney celebrates 'Freedom Day' after lockdown
Sydney's cafes, gyms and restaurants welcomed back fully vaccinated customers on Monday after nearly four months of lockdown, as Australia aims to begin living with the coronavirus and gradually reopen with high rates of inoculation.
#Sydney#FreedomDay#Lockdown#SydneyReopens#Australia#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖