Как разделить строку с 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
⚠️ We’ve been silent since September 9 on X (twitter) after our account was hacked, but we’ve just recovered it. This came as Venezuela faces new imperialist threats, while VA continues countering mainstream media lies.
👉 Stay tuned for lots of new content: x.com/venanalysis
#Venezuelanalysis
⚠️ Our X (Twitter) account @venanalysis has been hacked, just as US military threats against Venezuela intensify and mainstream media joins the chorus.
We’re working to recover it.
👉 Stay tuned here for updates.
#Venezuelanalysis
Venezuelanalysis is an independent outlet, free from corporate and political backers. Our mission to report on Venezuelan grassroots struggles is unwavering, but we need your support!
📍Make a one-time donation or subscribe to help us reach our goal here: https://venezuelanalysis.com/donate/
#Venezuelanalysis#IndependentJournalism#IndependentMedia#Fundraising
Oppose Trump’s War, Support Venezuelanalysis!
For over 20 years, we’ve stood with the Venezuelan people in their struggle for sovereignty. We’ve exposed US-backed aggression, documented grassroots resistance, and challenged dishonest media narratives.
Every contribution keeps this work alive. Click here to donate 👉https://venezuelanalysis.com/donate/
#Venezuelanalysis#Fundraising2025#IndependentMedia#Venezuela#SupportIndependentMedia
Fundraising 2025! 💪
We launch our yearly fundraising at a moment that feels more critical than ever. With Trump openly threatening to attack Venezuela and the corporate media beating the war drums, independent media must fight back.
For years, Venezuelanalysis has reported from the ground with accuracy and integrity; from documenting popular power to exposing dishonest narratives around sanctions. Today, our task is clear: counter war propaganda and defend peace and Venezuelan sovereignty.
Our work is 100% supported by readers and followers. That’s what keeps us independent. If you value this project, please consider making a donation or becoming a subscriber. Every contribution strengthens our ability to continue reporting in this historic moment.
Click here to donate 👉https://venezuelanalysis.com/donate/
#Venezuelanalysis#Fundraising2025#IndependentMedia#Venezuela#SupportIndependentMedia
🎥 VIDEO | Venezuela's Workers: Bonuses, Frozen Wages, and a Labor Law Under Threat
Venezuela’s minimum wage remains frozen while worker income is increasingly tied to discretionary bonuses. At the same time, proposed changes to the country’s landmark labor law are raising alarm among labor organizations.
Are workers’ rights being quietly dismantled?
Watch the video to learn more: https://youtu.be/rJJLUiLj2NQ
#Venezuela#WorkersRights#LaborLaw#WorkingClass#Venezuelanalysis