Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
🎉 AIRDROP MADNESS STARTS THIS SATURDAY! 🎉
Hey NeuralHubs fam—ready to turn your invites into cold, hard cash? 💸
We’re kicking off Weekly & Monthly Referral Airdrops, and you don’t want to miss this. 🤑
🚀 Weekly Airdrop: $200 up for grabs!
🥇 1st Place: $100
🥈 2nd Place: $60
🥉 3rd Place: $40
💰 Monthly Airdrop: $1,000 prize pool!
🥇 1st Place: $500
🥈 2nd Place: $300
🥉 3rd Place: $200
🔗 How to earn:
✅ Share your referral link (get it from the bot)
✅ Every friend who joins = 1 referral
✅ Referrals count toward both weekly & monthly leaderboards
✅ Plus, you get 20,000 tokens for every referral!
💥 It all kicks off this Saturday—so get your links ready, rally your crew, and start climbing the leaderboard.
🏆 More friends = More tokens = More cash. Let’s gooo!
😈 Payment: Crypto
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews → Soon @NeuralHubsNews
#️⃣#NeuralHubAI#Airdrop#ReferralContest#CryptoRewards
➖➖➖➖🔺
📰 AI News Update: 🤖
In the world of artificial intelligence, researchers have made significant strides in natural language processing. A new model developed by a team at a leading university has surpassed previous benchmarks in understanding context and nuances in text. This advancement could revolutionize chatbots, translation services, and content analysis tools.
Moreover, a breakthrough in AI ethics has been achieved with the development of a framework that prioritizes fairness and transparency in machine learning algorithms. This approach aims to mitigate biases and discrimination, ensuring AI systems make ethical decisions in various applications.
On the business front, tech giants are investing heavily in AI-driven solutions to enhance customer experiences and streamline operations. Companies across industries are increasingly leveraging AI to drive innovation...
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#ReferralContest#EarnTokens#WeeklyAirdrop
➖➖➖➖🔺
🚀 Referral Contest Heating Up – $200 Weekly Prize!
The race is ON, and here are your current top referrers:
🥇Amir – 30 referrals
🥈Pixel Wiz* – 29 referrals
🥉Ref Champ* – 23 referrals
But it’s not over yet — you still have time to climb the leaderboard and win your share of the $200 prize this week!
⚡️Just invite your friends using your referral link
😵Every referral brings you closer to the top
🏆Top 3 win: $100 • $60 • $40
Let’s go! Start inviting now and grab that top spot! 📈
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#ReferralContest#EarnTokens#WeeklyAirdrop
➖➖➖➖🔺