Как разделить строку с 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
Upgrade your skills for free:
🧑🎓Master Course : Making the Business Case for Sustainability
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Teaching Methods, Teaching Quality & Teaching Delivery 3.0
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Master Course in Smart Cities, Urban Planning & Development
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Master Course in Corporate Social Responsibility (CSR)
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Master Course in Climate Change Impact on Business
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Multigenerational Leadership & Reskilling Your Organization
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Master Course in Project Management 2.0
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓AI-Powered Change Management for Digital Transformation
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Curso Completo de Mikrotik. Configuraciones y mucha Práctica
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Programador Java en 37 Días Con práctica de Entrevista y más
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓NumPy, SciPy, Matplotlib & Pandas A-Z: Machine Learning
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Carbon Capture (CCUS): Governance, Policy, & Social License
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓The Complete JavaScript Course: From Zero to Expert
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Certificado Profissional em Liderança e Gestão
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Mastering Manus: AI Automation for Marketing & Content
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓AI for Business Analysts
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Entrepreneurial Guide to AI Strategy
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning
Upgrade your skills for free:
🧑🎓Emotional Intelligence in Teams and Collaboration ( EQ )
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓Data Visualization: Advanced Storytelling for Sales Success
▪️▪️▪️▪️▪️▪️▪️▪️
🧑🎓AI-Driven Business Process Modeling
▪️▪️▪️▪️▪️▪️▪️▪️
⚠️ Limited time offers
🧑🎓🧑🎓🧑🎓
https://SkillDiscounts.com/
@SkillDiscounts
#Learning_for_free
#FreeCoupon
#FreeLearning