Как разделить строку с 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
🔥NEW RELEASE🔥
😁Duck Under Masterclass by Cole Abate😁
➡️The Duck Under combines pressure and speed, blending the control of traditional passing with the tempo and sharpness of the modern game, allowing the guard passer to dictate the pace of the fight.
➡️The Masterclass includes more than 5+ hours of entries, concepts, transitions, and submissions. Throughout the 40 classes, Cole demonstrates the effectiveness of the position, and how the Duck Under completely neutralizes the guard player by removing their ability to setup sweeps or submissions.
$̶1̶7̶9̶😍$19.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#ColeAbate#GuardPassing#Gi#AOJ
💁♀️Buy
💁♀️
😁Modernized Headquarters Passing By Shawn Melanson😁
➡️Unlock the secrets to one of the most dominant and versatile passing positions in Brazilian Jiu-Jitsu with Modernized Headquarters Passing by Shawn Melanson
➡️As an up-and-coming No-Gi competitor who has conquered tournaments at the highest levels, Shawn brings his proven expertise directly to your training. In this comprehensive instructional series, he breaks down the Headquarters Position, a game-changing technique that can be used against nearly every guard in the sport.
➡️With step-by-step guidance, Shawn reveals how to enter, control, and pass from the Headquarters Position, offering you a wide array of strategic options to dominate your opponent.
$79😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#ShawnMelanson#BJJFanatics#GuardPassing#NoGi#Headquarters
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Things I Didn't Show To Craig Jones: Maintaining An Advantage Over Time - Outside Passing By Jozef Chen😁
➡️Unlock the secrets to unstoppable no-gi guard passing with JPoint Camping, the latest BJJ instructional from one of the most elite no-gi competitors today, Jozef Chen.
➡️In this systematic instructional, Jozef guides you through the step-by-step process of dismantling even the most difficult no-gi guards, using a series of tried-and-true methods refined over years of high-level competition.
➡️Transform your guard passing into a dominant, methodical force, and learn how to effortlessly break through any guard. With Jozef Chen’s expert guidance, you’ll develop the mindset, precision, and fluidity needed to consistently control the pace and flow of your no-gi matches.
$127😍$11.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#JozefChen#CraigJones#CJI#GuardPassing
💁♀️Buy
💁♀️