Как разделить строку с 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
🎓✨ CONGRATULATIONS! ✨🎓
To all Jimma University students who passed the exit exam and will graduate this Saturday! 🌟
Your hard work and determination have led to this proud moment. Wishing you a future full of success, peace, and new beginnings! 🌍🎉
#JIFAR CAREER
Eid Mubarak! ✨ May this special day bring you joy, peace, and countless blessings. Wishing you and your loved ones happiness, prosperity, and togetherness. Enjoy the festivities and spread kindness! 🌙💙
#JIFAR CARRER
For those of you who find creativity challenging, try this
✨ Team up with someone who has similar goals or works on related projects.
Their ideas and experiences might open new doors and inspire fresh solutions.
Collaboration can increase your creativity and lead to amazing results—give it a try! 👊
#JIFAR TUTOR
@JifarSupport
Honoring and Memorizing this photo☺️😊
## JIFAR TUTOR:Unleash Your Potential, Embrace the JImma Aba Jfar Legacy
JIFAR TUTOR:Where History Inspires Your Future
> At JIFAR TUTOR, we're dedicated to bringing history to life, inspiring students to unlock their own potential and shape their own futures.
> Our Legacy
> * Student Spotlight Series: Hear from real students who are finding their own voices and shaping their own destinies, inspired by JImma Aba Jfar's example.
> * "Beyond the Textbook" Experiences: Explore local historical sites, connect with experts, and delve deeper into JImma Aba Jfar's legacy through real-world experiences.
> With JIFAR TUTOR, you'll:
> * Develop essential skills for success in the 21st century: critical thinking, communication, and problem-solving.
> * Discover your own leadership potential and find inspiration for creating positive change.
📝Visit Our channels: @JIFAR1
🛎Call 24/7':@JifarSupport 0953484398
#JIFAR TUTOR
#JIFAR TUTOR
New Job opening‼️
🎆We are Jifar Tutor🎆
✍️Place: Tshire
✍️Student: Grade 11
✍️Duration: 4 or 3 in a week
✍️Salary: monthly by Agreement
✍️#Females apply for this job
✍️ Subject All
📖We need punctual and who have excellent professional ethics and applicants for this position.
#Jifar HomeTutor #ጅፋር#ቤትለቤት(Online) #አስጠኚ
#በፈለጉን#ሁሉ#አለን! #
#የልጅዎ#እና#የርስዎ#ቀዳሚ#አጋር!
በዚህ ያናግሩን @JifarSupport
🎆 Jifar Tutor your choice🎆
ከታች ያለዉን የቴሌግራም ቻናላችን ይቀላቀሉ
👉@Jifar1
✅Job status - CLOSED‼️