Как разделить строку с 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
Embark on a journey of progress and transformation! 🚀
Visit https://9years.mygov.in/ to discover the incredible achievements of the Modi Government in the last 9 years. Explore the remarkable strides made across various sectors, from healthcare to infrastructure, education to governance.
#9YearsOfSeva
🇮🇳 In 9 years, the Modi Government achieved an unprecedented combination of speed and scale, ensuring the timely completion of all projects!
From highways and airports to digital infrastructure, India witnessed an era of efficient governance that propelled progress at an unmatched pace.
#9YearsOfSeva
https://youtu.be/L7x-8aIjSQ0
"सेवा, सुशासन और गरीब कल्याण को सर्मपित 9️⃣ साल" 🇮🇳
आइए इस वीडियों के माध्यम से देखें कैसे, बीते 9 वर्षों में #NewIndia जनसामान्य की आकांक्षाओं को पूरा करते हुए निरन्तर नई-नई उपलब्धियां रच रहा है।
#9YearsOfSeva
https://youtu.be/L7x-8aIjSQ0
"सेवा, सुशासन और गरीब कल्याण को सर्मपित 9️⃣ साल" 🇮🇳
आइए इस वीडियों के माध्यम से देखें कैसे, बीते 9 वर्षों में #NewIndia जनसामान्य की आकांक्षाओं को पूरा करते हुए निरन्तर नई-नई उपलब्धियां रच रहा है।
#9YearsOfSeva
https://youtu.be/L7x-8aIjSQ0
बीते 9 वर्षों में माननीय प्रधानमंत्री #NarendraModi के नेतृत्व में केंद्र सरकार द्वारा विभिन्न क्षेत्रों में हुई अविश्वसनीय उपलब्धियों को जानने हेतु अभी विजिट करेः https://9years.mygov.in/
#9YearsOfSeva
Don't miss this remarkable video showcasing how the Modi government's relentless efforts over the past 9 years have propelled the development and preservation of India's rich cultural heritage.
Visit: https://youtu.be/scGbw2m8ook
#9YearsOfPreservingCulture
#9YearsOfSeva
Check out this captivating snapshot showcasing the Modi government's remarkable progress in preserving and promoting India's cultural heritage. From restoring ancient monuments to revitalizing traditional arts, their efforts over the past 9 years have made India's legacy shine brighter than ever.
#9YearsOfPreservingCulture
#9YearsOfSeva
📈 India keeps dominating the digital payment landscape! 💸🇮🇳 With innovative solutions and widespread adoption, we're leading the way towards a cashless economy. 💻
#9YearsOfTechForGrowth#9YearsOfSeva
Empowering street vendors for a brighter future!
PM SVANidhi is transforming lives & livelihoods, providing financial support, & fostering entrepreneurship among street vendors in India
#9YearsOfGaribKalyan#9YearsOfSeva
Check out this captivating snapshot showcasing the incredible strides made in environment and sustainability during the 9 years of the Modi government.
#9YearsOfSustainableGrowth#9YearsOfSeva