Как разделить строку с 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
#Antimicrobials are not always needed when you are feeling unwell.
Antibiotics should only be prescribed by healthcare professionals after an appropriate diagnostic test.
Be an #AntimicrobialResistance guardian.
#Antimicrobials are not always needed when you are feeling unwell.
Antibiotics should only be prescribed by healthcare professionals after an appropriate diagnostic test.
Be an #AntimicrobialResistance guardian
#Antimicrobials are not always needed when you are feeling unwell.
Antibiotics should only be prescribed by healthcare professionals after an appropriate diagnostic test.
Be an #AntimicrobialResistance guardian
#Antimicrobials are not always needed when you are feeling unwell.
Antibiotics should only be prescribed by healthcare professionals after an appropriate diagnostic test.
Be an #AntimicrobialResistance guardian
#Antimicrobials are vital in fighting infectious diseases across humans, animals, and plants.
However, their effectiveness is diminishing, leading to a growing and urgent crisis known as #AntimicrobialResistance.
Let’s promote the responsible use and work together to combat #AMR.
#Handwashing is a basic and effective tool against infections.
If we do not become sick, we would not need to use #antimicrobials.
Encourage your loved ones to practice frequent #handwashing with soap under running water.
Do your part to prevent #AntimicrobialResistance
#Antimicrobials are becoming less effective against common infections in animals & humans.
🚫 Do not self-medicate
✅ Visit a healthcare professional when sick
Everyone has a role to play to ensure #antimicrobials continue to work.
#AMR#WAAW2023
#AntimicrobialResistance is a global concern affecting everyone, everywhere, including users & non-users of #antimicrobials
Our National Action Plan for Antimicrobial Resistance incorporates a #OneHealth approach to contain #AMR in Nigeria
Read & share:
https://ncdc.gov.ng/themes/common/docs/protocols/77_1511368219.pdf
#AntimicrobialResistance is one of the top 10 health threats in the world.
Everyone everywhere, including users and non-users of #antimicrobials have a role to play to prevent #AMR.
#BeAntimicrobialAware
Every year, the National Antimicrobial Resistance Technical Working Group joins the global community to raise awareness of the dangers of misuse or overuse of #antimicrobials.
Fighting #AMR is a global endeavour that must be addressed through a #OneHealth approach as evident in this year's theme of #WAAW2023: ‘Preventing #AntimicrobialResistance together”
🔗Press Release
https://ncdc.gov.ng/news/504/nigeria-joins-the-global-community-to-commemorate-world-antimicrobial-awareness-week-%28waaw%29
Misuse or overuse of #antibiotics💊 & other #antimicrobials can reduce its effectiveness in treating common infections in animals & humans.
From 18th-24th November, we are joining the global health community to mark the annual #WorldAntimicrobialAwarenessWeek2022 .
#StayTuned
#AntimicrobialResistance is when medicines like #antimalarials, tetracycline, septrin, and amoxicillin no longer treat diseases they cured previously.
Everyone everywhere, including users and non-users of #antimicrobials has a role to play to prevent #AMR.
#BeAntimicrobialsAware