Как разделить строку с shell-командой на отдельные аргументы в виде списка?
Если сделать просто сплит по пробелу то получим то что надо, кроме случаев со вставками текста с пробелами. Например так:
>>> '-arg "I Am Groot"'.split(' ')
['-arg', '"I', 'Am', 'Groot"']
Чтобы учитывать текст в кавычках как единый аргумент можно воспользоваться функцией shlex.split()
Кто читает мой канал давно, уже в курсе.
А что делать, если нужно обратное действие? Объединить аргументы из списка в строку и при этом добавить кавычки в аргумент с пробелами.
Конечно, если вы используете subprocess то он сам всё разрулит. Но если вам нужна именно команда одной строкой, то можно воспользоваться готовой функцией в том же subprocess.
>>> from subprocess import list2cmdline
>>> list2cmdline(['-arg', 'I Am Groot'])
'-arg "I Am Groot"'
Он также позаботится об экранировании уже имеющихся кавычек
>>> list2cmdline(['-arg', 'I Am "Groot"'])
'-arg "I Am \"Groot\""'
А вот так он может "схлопнуть" в команду JSON
>>> list2cmdline(['--json', json.dumps({'key': 'value'})])
'--json "{\"key\": \"value\"}"'
_______________
Возможно кто-то спросит, а зачем соединять аргументы в строку если subprocess сам это сделает а os.system не наш путь?
Мне как-то потребовалось отправлять команду на удалённое выполнение и в API поддерживалось указание команды только строкой. Так что всякое бывает)
#libs#basic
🚀 Join us on a journey to revolutionize the world of asset #tokenization and #engagement!
🌍 Our mission is clear: empower individuals and enterprises globally through innovative solutions, strategic partnerships, and #community-driven initiatives.
Learn more at: https://goplatform.io/blog/revolutionizing-enterprise-engagement-the-power-of-asset-tokenization-with
Together, we can create a transformative ecosystem where everyone has the opportunity to thrive.
🌞 Bonjour à tous nos chers abonnés ! 🌍🫵🏽
Nous vous souhaitons un excellent mercredi rempli d'énergie et de détermination. ✨💪🏾La lutte continue, restons unis et solidaires !
#Force#Engagement#Ensemble
@egountchibehanzinTV
Channel: Instagram Accounts & Services
Members: ~3.49K
💢 Username: @buyinstaaccounts
Description:
We Sell Instagram Accounts, Followers, Likes, Views, Commmets Or Any Other Service Regarding Instagram. With 8 Years Of Experience.
🏷 Tags: #games_apps
#instagram#accounts#social_media#followers#engagement
https://telegramchannels.me/channels/buyinstaaccounts
TVision Secures $1.5M Funding
TVision has raised $1.5M in funding as of December 16, 2024. The company utilizes advanced computer-vision technology to analyze viewer engagement for both Linear and CTV, offering person-level insights into viewing habits.
#Funding#TVision#Technology#ViewerEngagement#CTV#Linear#Insights#ComputerVision#Analytics#Viewership#Audience#Engagement#Media#Streaming#Data#Research#Investment
Telegram Unveils Major NFT Update
🎉 Telegram introduces a big update allowing gifts and stickers to be converted into NFTs. Gifts gain unique traits like emotions, backgrounds, and colors, enhancing their individuality and value. Rare traits will be limited to 10% of users, creating opportunities for resale at higher prices. Gifts can be converted for 25 Stars, while minting NFTs incurs network fees. Future integration with platforms like Fragment or GG is expected for seamless NFT creation. 🐸 The latest highlight is a unique frog gift gaining traction!
For more details, visit: Full Update
#Telegram#NFT#Gifts#Crypto#Updates#Blockchain#Stars#Minting#Fragment#GG#Frogs#RareItems#DigitalAssets#Community#Market#Trading#Tech#Innovation#SocialMedia#Engagement#CryptoTrends
AI Video Editor Raises $500K
Diffusion Studio has secured $500K in funding as of December 4, 2024. Their AI Video Editor simplifies video editing with advanced features such as Magic Cut, Text-Based Editing, and Instant Auto-Captioning, catering to creators and businesses aiming to enhance their video production efficiency.
#AI#VideoEditing#Funding#Technology#Creators#Influencers#Business#Automation#Software#Innovation#EditingTools#VideoProduction#TextBasedEditing#AutoCaptioning#Workflow#Engagement#Professional#ContentCreation#Creativity#Efficiency