Ранее мы уже говорили о том, как выполнить какой-либо код перед открытием интерактивной консоли.
Расскажу еще один способ! На самом деле, даже запустив интерпретатор в обычном режиме с выполнением скрипта из файла вы можете в любом месте активировать интерактивный режим. Или даже несколько по очереди. За это отвечает модуль 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
🚨🇺🇸MICROSOFT AI INVESTMENTS TRIGGER MASSIVE TECH SELLOFF FEARS
🔹 MSFT crashes 15% YTD to $410 after revealing $37.5B AI capex spending — Wall Street panicking over return on investment timeline 💰📉
🔹 Tesla faces March 9 NHTSA compliance deadline for 2.88M FSD vehicles — potential $139M penalty sparks 2% pre-market drop to $388 🚗⚡
🔹 Software sector hemorrhages $800B as S&P Software Index plunges 13% in February — biggest tech rotation since 2002 dot-com crash 💸
Silicon Valley's AI gold rush hitting reality wall — investors fleeing to consumer staples as tech's worst quarter since 2008 unfolds 🤔💥
#TechStocks#USNews
@america
📈Volatility Log: Skew Says Tech Stocks and Europe Rates Aren't Done
Despite seemingly calm spot markets, the volatility log reveals persistent hedging demand driven by intertwining macro catalysts including key tech stocks and European inflation trends. We examine...
🔗Read Full Analysis
🎯 SPECIAL OFFER: 15% OFF
💸 Coupon Code: salenow15%
🚀 Upgrade to premium signals → https://markets.fxpremiere.com/en/signals?utm_source=telegram
📰 Stay ahead — get breaking financial news & analysis at https://markets.fxpremiere.com/en?utm_source=telegram
#Volatility#TechStocks#InterestRates
🚀 Hong Kong Stocks Open Lower as Tech Shares Decline
Hong Kong stocks opened lower today, with the Hang Seng Index dropping 0.71% and the Hang Seng Tech Index falling 0.69%. According to Jin10, technology stocks led the decline, with Baidu (09888.HK) down over 3% and NetEase-S (09999.HK) falling more than 2%.
#HongKongStocks#HangSengIndex#HangSengTechIndex#TechStocks#Baidu#NetEase
🚀 STOCKS | Hong Kong's Hang Seng Index Retreats After Previous Surge
On April 9, Hong Kong's Hang Seng Index experienced a pullback following a significant rise of nearly 800 points the previous day. According to Jin10, the index opened over 100 points lower in the morning and briefly fell more than 200 points to reach 25,653.63 points before recovering slightly. By midday, the Hang Seng Index closed down 0.35% at 25,803.12 points, while the Hang Seng Tech Index fell 1.26% to 4,861.39 points. The total market turnover for the Hang Seng Index reached HKD 126.652 billion.
In terms of sector performance, optical communication and computing infrastructure stocks led gains, while the innovative drug concept saw a brief surge in early trading. However, most technology stocks underwent a correction, with real estate and gold stocks experiencing notable declines. Among individual stocks, Yangtze Optical Fibre and Cable Joint Stock Limited Company (06869.HK) rose 3.2%, WuXi AppTec Co., Ltd. (02359.HK) increased by 3.53%, Kingdee International Software Group Company Limited (00268.HK) fell 5.49%, Kuaishou Technology (01024.HK) dropped 3.55%, and Longfor Group Holdings Limited (00960.HK) decreased by 4.07%.
#HangSengIndex#HongKongStocks#StockMarket#TechStocks#RealEstate#Gold#MarketPullback#Trading#Investment
🚀 Lumentum Holdings Sees 132% Return Amid Nvidia's $2 Billion Investment
Lumentum Holdings has experienced a remarkable 132% return this year, transforming a $1,000 investment in January into $2,320 by April. According to NS3.AI, this impressive rally is attributed to Nvidia's substantial $2 billion acquisition of ultra-high-power lasers and capacity rights for next-generation optical interconnects. The strategic move by Nvidia has significantly boosted investor confidence in Lumentum Holdings, driving its stock performance upward.
#LumentumHoldings#Nvidia#Investment#StockMarket#TechStocks#OpticalInterconnects#InvestorConfidence#HighReturn
Exodus Debuts on NYSE with 36% Gain
Exodus, a developer of non-custodial software, made its debut on the New York Stock Exchange (NYSE) under the ticker EXOD. In its first trading session, shares surged 36%, bringing the company's market capitalization to $1.4 billion. For more details, visit ForkLog.
#Exodus#NYSE#IPO#StockMarket#Investing#Growth#TechStocks#FinancialNews#Blockchain#Software#NonCustodial#MarketCapitalization#Trading#WallStreet
DeepSeek AI Disrupts Tech and Crypto Markets
DeepSeek, a Chinese AI startup, launched its DeepSeek-R1 model, rivaling OpenAI's offerings but at significantly lower costs. The buzz around DeepSeek has led to a $1 trillion drop in US tech stocks, with Nvidia shares tumbling nearly 10%. Experts caution against hasty conclusions regarding the market reaction. Amidst this, investment director Michael van de Poppe advises Ethereum investors to stick to long-term strategies, predicting positive growth for Ethereum and Solana in 2025 due to lower interest rates and geopolitical instability. Read more about the implications of DeepSeek's emergence on the tech landscape here.
#AI#DeepSeek#Crypto#Ethereum#Solana#TechStocks#Nvidia#MarketCrash#Investing#Finance#Web3#MachineLearning#ArtificialIntelligence#Startups#China#Innovation#Stocks#HedgeFund#DeFi#Trends#MarketTrends