Как разделить строку с 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
🇺🇸#LosAngeles. Wild teens ransack Chevron store in Lincoln Heights in broad daylight.
Another SoCal store is taken over by rampaging teens racksacking aisles, grabbing whatever they can. This time, a Lincoln Heights Chevron station is hit. The frustrated store managers who want police to do more to stop the takeovers.
Follow us -> LiveLeak
Please do not curse the victims of the American fires. There are many innocent civilians and pro-Palestinian people. Those elites had already fled before the fires came.
#LosAngeles
This is absolutely disgusting and heartbreaking.
Homeless addicts on Skid Row in LA are using innocent dogs to test their drugs for fentanyl. These poor animals are being fed deadly substances, abused, neglected, sold for drugs, and thrown away like trash.
Volunteers from Starts With One Today are risking their lives to rescue these dogs with zero support from the city.
How has Mayor Karen Bass and LA leadership let this horror continue? Animals are suffering and dying in plain sight while officials do nothing.
This is pure cruelty. Where is the outrage? Where is the action?
#SaveSkidRowDogs#AnimalAbuse#LosAngeles
🔹👉🏻@SherriTenpenny
PERFECT RING FORMED OVER LOS ANGELES
This appeared high above L.A. just after dusk.
A bright linear trail stretched across the sky — and around it, a smooth circular arc expanded and held its shape.
The symmetry is what stands out.
A straight line through the center.
A clean curve wrapping around it.
It lingered long enough for people across the city to stop and stare.
Los Angeles, California.
Did you catch this from where you are?
MrMBB333
👇 Drop your city.
#MrMBB333#SkyWatch#LosAngeles
#Wildfires ravage #California, leaving 5 people dead and over 27,000 acres burned. #LosAngeles Authorities warned casualties may rise as the fires remain uncontained.
USA Major League Soccer🇺🇸
2026-04-19 23:00 UTC
Los Angeles FC vs. San Jose Earthquakes
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: San Jose Earthquakes 1:4
#LosAngeles#SanJoseEarthquakes
#Football#USAMLS
As #LosAngeles burns and #firefighters face a severe water crisis, criticism is mounting against #billionaires Stewart and Lynda #Resnick, whose $13B agricultural empire consumes more water than LA and SF combined.
#PalisadesWildFire
USA Major League Soccer🇺🇸
2026-05-10 20:30 UTC
New York City FC vs. Columbus Crew
Predicted outcome: New York City FC✅
Predicted score: 3:2
Actual: New York City FC 3:0
#NewYorkCity#ColumbusCrew
2026-05-10 23:00 UTC
Minnesota United FC vs. Austin
Predicted outcome: Minnesota United FC❌
Predicted score: 2:1
Actual: Draw 2:2
#MinnesotaUnited#Austin
2026-05-11 01:00 UTC
Los Angeles FC vs. Houston Dynamo
Predicted outcome: Los Angeles FC❌
Predicted score: 2:1
Actual: Houston Dynamo 1:4
#LosAngeles#HoustonDynamo
#Football#USAMLS