Как разделить строку с 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🔥
😁Systematically Attacking The Half Guard and Scrimmaging: Whizzer vs Underhook by Gordon Ryan😁
➡️In Systematically Attacking The Half Guard and Scrimmaging: Whizzer vs Underhook, Gordon Ryan breaks down one of the most common—and misunderstood—positions in all of Jiu-Jitsu, and turns it into a clear, repeatable system you can rely on every time.
➡️Widely regarded as the most accomplished No-Gi grappler of all time, Gordon is known for his unmatched submission rate and his ability to teach complex positions with precision and clarity. This series is a perfect example of that.
$349😍$24.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#GordonRyan#Sweeps#NoGi#NewWave
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Knee Lever Masterclass by Brian Glick😁
➡️The Knee Lever Masterclass from Brian Glick, a John Danaher black belt and one of BJJ Fanatics’ best-selling instructors, is your complete system for turning one of Jiu-Jitsu’s most underrated techniques into a powerful, all-position weapon
➡️Known for his world-class instruction, clear communication, and simple, effective systems, Brian once again delivers an instructional packed with precise details and universal concepts that make complex ideas easy to apply.
$197😍$14.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#BrianGlick#Sweeps#NoGi#NewWave
💁♀️Buy
💁♀️
🔥NEW RELEASE🔥
😁Master The Move: The Butterfly Guard Sweep Sumi Gaeshi by John Danaher😁
➡️In Master The Move: The Butterfly Guard Sweep Sumi Gaeshi, Danaher breaks down what many consider the single most effective sweep in grappling.
➡️Now, for the first time, Danaher reveals the complete system behind the Sumi Gaeshi sweep from butterfly guard — the same position that connects effortlessly to leg locks, back takes, and devastating top control sequences.
$197😍$19.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#JohnDanaher#Sweeps#NoGi#NewWave
💁♀️Buy
💁♀️
😁Top 10 Sweeps and Reversals by Magid Hage😁
➡️In Top 10 Sweeps and Reversals, Magid Hage breaks down the most basic, high-percentage sweeping techniques that every Brazilian Jiu-Jitsu practitioner should have in their game.
➡️This course focuses on simplicity, timing, and efficiency, showing you how to off-balance your opponent and reverse the position with minimal strength and maximum control.
$79😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
👑MasterClass
✈️@bjjfanaticsinstructionals
#MagidHage#Sweeps#NoGi#IBJJF
💁♀️Buy
💁♀️
😁Precision Sweeps And Wrestle Ups From The Seated Position By Shawn Melanson😁
➡️Master the art of disrupting standing passers with surgical precision. In his fourth and most dynamic instructional to date, best-selling BJJ coach Shawn Melanson delivers a comprehensive system for attacking from the seated guard — blending positional off-balancing, precision timing, and relentless wrestle-ups to systematically frustrate and dismantle your opponent’s passing game.
➡️Shut down standing passers with precision sweeps, wrestle-ups, and off-balancing tactics from seated guard in Shawn Melanson’s latest high-level BJJ instructional.
$79😍$9.99😍
❗️Channel Info and FAQ (MUST CHECK BEFORE BUY)❗️
📱Payment: 📱📱📱
💰Submeta FOR FREE
🌈UFC Picks
👑MasterClass
✈️@bjjfanaticsinstructionals
#ShawnMelanson#Sweeps#NoGi#WrestleUp
💁♀️Buy
💁♀️