Как разделить строку с 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
BitFuFu Secures Major Mining Deal
BitFuFu signs two-year agreement with Bitmain to purchase up to 80,000 S-series bitcoin mining machines for self-operated mining. More details on the deal here: link
#Bitcoin#BitFuFu#Bitmain#Mining#Miners#Crypto
🖤Blockchain Life 2025 Sum up
Dubai, Oct 23, 2024 — The 13th edition of the Blockchain Life Forum, the premier gathering for cryptocurrency leaders worldwide, recently concluded with an astounding attendance of over 12,119 participants.
😎 The forum showcased over 200 esteemed speakers, featuring industry pioneers and executives from top companies, including #OKX, #CoinMarketCap, #Bitmain, #Bybit, #Binance, #AnimocaBrands, #Circle, #BingX, #ICP, #Kraken, #TON and many more.
📱 The exhibition of crypto companies featured 125 amazingly beautiful booths. Major players such as #OKX, #Bitmain, #BingX, #KuCoin, #Bitget, #ListingHelp, and #Uminers.
🎧 As a spectacular finale to the forum, participants enjoyed the Legendary #AfterParty at one of the world’s premier clubs, SKY2.0. This informal networking event provided a platform for top industry figures to connect, complemented by a dazzling live performance from internationally celebrated artist French Montana, who thrilled over 1,200 attendees with his chart-topping hits.
See you at Blockchain Life 2025!
The early bird tickets and sponsorship application for Blockchain Life 2025 are already open – follow the link:
https://blockchain-life.com