Как разделить строку с 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
📍 Road from Surum to Tashaul
📅 Video recorded on February 26
The village of Surum (Sur-um) is located in Tashkent Region, bordering the Sergeli and Yangihayot districts of Tashkent (about 9 km from the center of Sergeli).
The video shows thick dust from operating crushers. According to local residents, this situation has been ongoing for a long time.
Residents complain about:
▪️ constant loud noise;
▪️ dense dust in the air;
▪️ difficulty breathing and worsening living conditions.
The community asks authorities to pay attention to the environmental situation and take measures to reduce dust and noise levels.
❗️ The situation requires inspection by responsible agencies and an assessment of its impact on the environment and public health.
#Environment#TashkentRegion#Dust#Noise#EnvironmentalIssue
☘️ Follow the latest environmental news on @ekologuz. Send your suggestions and feedback via @eklguz_bot!
Meeting with animal capture services of Tashkent region
Representatives of NGO «HAYOT», together with the Head of the Security Service of the Ministry of Internal Affairs of the Republic of Uzbekistan, Lieutenant Colonel Rovshan Pirimkulov, held a meeting with animal capture services from Yangiyul, Angren, Akhangaran, Buka, Pskent, Nurafshan, Bekabad, Urta Chirchik, Kibray, Bostanlyk, and Parkent.
Key conclusions:
✅ Animal capture activities must be carried out strictly within the law and in compliance with humane standards; cruel methods are unacceptable.
✅ Violations will receive legal assessment by competent authorities.
✅ Cat capture has been suspended — the “Mushukkent” project (sterilization and humane population control) continues.
✅ Issues related to salaries, equipment, and inventory for humane capture were discussed.
✅ Public awareness activities are planned, along with the possible allocation of land for state animal shelters.
💡 The meeting was held in a constructive dialogue format and may become a starting point for real changes in the field of animal welfare.
#NNOHAYOT#HumaneCapture#Mushukkent#TashkentRegion#AnimalProtection
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
Uzbekistan has opened a criminal case against penitentiary system officers after a man previously convicted of pedophilia escaped from a colony and assaulted a third-grade girl in the Akhangaran district. The National Agency for Social Protection is overseeing the case.
https://yep.uz/en/2025/10/uzbekistan-investigates-police-actions-after-convicted-pedophile-escape/
#Uzbekistan#Akhangaran#TashkentRegion#InteriorMinistry#Investigation#SocialProtection#Law