Как разделить строку с 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
🇺🇿Biznes va tadbirkorlik oliy maktabi 9-may – Xotira va qadrlash kuni bilan barchangizni chin dildan qutlaydi!
🗓 9-may – Xotira va qadrlash kuni munosabati bilan Vatanimiz tinchligi va farovonligi uchun jang maydonlarida buyuk qahramonlik ko‘rsatib, halok bo‘lgan mo‘tabar ota-bobolarimizni xotirasi barhayot bo‘lsin, front ortida fidokorona mehnat qilgan faxriylarimizni hamda butun xalqimizni samimiy muborakbod etamiz!
⏩ O‘z navbatida, urushdan keyin mamlakatni tiklash, jonajon O‘zbekistonimizni rivojlantirishga munosib hissa qo‘shib kelayotgan, tabarruk yoshga yetib, duogo‘yimiz bo‘lib yurgan nuroniy otaxonu onaxonlarimizga cheksiz minnatdorligimizni bildiramiz.
🟥 Vatanimiz tinch, osmonimiz musaffo, mustaqilligimiz abadiy bo‘lsin aziz Yurtdoshlar!
#GraduateSchool#Remembrance#Appreciation
🌐Web-site |
✅ Telegram |
✅Facebook |
🌐Instagram
Standing in remembrance of those who gave their lives for freedom.
To remember is to refuse indifference, and to defend the dignity and freedoms they died for.
面對今日仇恨與極右思潮再次抬頭,自問若為自由犧牲的靈魂泉下有知,會如何期望我們守護得來不易的價值?
#Remembrance#LestWeForget#永誌不忘
US Condemns Crocus City Hall Terror Attack on Anniversary
The US Embassy in Russia marked the second anniversary of the Crocus City Hall tragedy, expressing solidarity with victims’ families. The March 22, 2024 terror attack claimed 151 lives, including children, profoundly affecting many. The US emphasized that the memory of those lost remains strong over time.
#terrorattack#Crocus#USA#Russia#remembrance
The main news of Russia and the world ishere.
前往 #和平紀念日 典禮的乘客
可取道 #中環 站 出口 J3 - 香港會所大廈
#中環 站出口位置 👉metroride.hk/3F89wcu
該站 出口 J1 - 終審法院 將於 11 月 10 日(星期日) 10:00 關閉至 12:00 為止,使進出街道的人流更為暢順 🌺
#LestWeForget
#英魂不朽#永誌不忘
Use Exit J3 - The Hong Kong Club Building for #Remembrance Day Ceremony
Exit locations of Central 👉metroride.hk/3F89wcu
While Exit J1 - The Court of Final Appeal will be closed from 10:00 - 12:00, 10/Nov (Sun) for a smoother passenger flow to and from street level 🌺
Musical and Poetic Performance “The Spring is Coming Again to the World…”
On the eve of Victory Day, the Russian House in Brussels invites you to a special evening of music and poetry.
People’s Artist of Russia Oleg Pogudin and his Romance Theatre will present a programme dedicated to the memory of a generation whose youth fell upon the years of the Great Patriotic War.
The evening will feature poems and songs born in the harsh years of war — sincere, courageous, and filled with both the pain of loss and a bright hope.
🎹 Piano part: Oleg Weinstein, Honored Artist of the Russian Federation
📅 April 28
🕖 19:00–21:00
📍 Russian House in Brussels
🎟 Free admission upon registration
https://rushouse.be/event/musical-performance-the-spring-is-coming-again-to-the-world/
We warmly invite you to join this evening of remembrance, music, and poetry.
#RussianHouseBrussels#BrusselsEvents#Culture#Music#Poetry#OlegPogudin#Concert#CulturalDiplomacy#VictoryDay#Remembrance#RussianCulture#ArtAndCulture