Как разделить строку с 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
🚀#LOScoin is excited to announce that we have successfully completed $2 million in funding!
In this round of financing, Solana Foundation led the investment, and CMS Holdings, Impossible Finance, Yield Guild Games (YGG) and Monad and other well-known institutions followed the investment, helping LOScoin build a more powerful and interactive Web3 gaming social ecosystem 2.0
$LOS This round of financing also received strong support from @AI_mint__ CEO Keone Hon, further confirming our innovation and leadership in the Web3 gaming field.
🚀#LOScoin is excited to announce that we have successfully completed $2 million in funding!
In this round of financing, Solana Foundation led the investment, and CMS Holdings, Impossible Finance, Yield Guild Games (YGG) and Monad and other well-known institutions followed the investment, helping LOScoin build a more powerful and interactive Web3 gaming social ecosystem 2.0
$LOS This round of financing also received strong support from @AI_mint__ CEO Keone Hon, further confirming our innovation and leadership in the Web3 gaming field.
🚨📌🔗
🤑
🤙
🤙
🤙
🤙
🤙
🤙
🤑
🤑
It's time to show the unity and strength of the #LOScoin community
Vote for #LOScoin and accomplish great things
X: https://x.com/anndylian/status/1847137465762758958
🚨 Reminder: Remember to claim your referral income and game rewards every day!
🤙
🧐
😎
If you miss it, they will be burned after 24 hours
🤑
🤑
🤑
#LOScoin
🤑
🖤https://x.com/losgamecoin/status/1830543753670713509?s=46