Как разделить строку с 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
🔎Telegram May Be Quietly Testing a Feed like Feature
Telegram has recently introduced a new ‘Posts’ tab in Search, allowing users to easily discover content from public channels. This update comes roughly a year after the launch of #hashtagsearch, signaling Telegram’s continued focus on improving content discoverability.
This appears to be a soft launch of a potential future ‘Feed’ feature — offering users a scrollable stream of relevant #posts, possibly influenced by engagement metrics such as stars.
If fully implemented, this feature could significantly boost post visibility for channels, increase ad exposure for advertisers, and enhance ad revenue opportunities for creators. All indications suggest that Telegram is gearing up to roll out a #feed-based content experience, a move that could reshape how users browse and interact on the platform.
When the chat reaches 4,000 members or the channel 90,000, 10 group members will be allowed to create a post each, about a sfw topic of their own chosing. You must give @googlefactss permission to use your post and add it to the channel, with or without your username.
More details will come after we hit these numbers. Invite friends, family, and coworkers to join.
Do not spam/send links without permission of the place you send them in!!
Our group links are:
Main channel https://t.me/googlefactss
Group:
https://t.me/googlefactssgroup
@googlefactss📢👥
#Community#Permission#Posts#Growth#KeepTrackOfThisPost
@channely_bot
Qué puede hacer este bot?
Este bot es el mejor asistente para la gestión de canales en Telegram. Conecto los canales al servicio principal. ¡Incluyendo un rico entorno webUI de edición!
https://app.channely.co/
Idioma: Inglés
(visto en @BotsGram.cu)
#canales, #canal, #gestión, # administración, #richeditor, #posts, #schedule, #polls, #comment, #commenting, #reactions, #editor, #share, #buttons, #webui, #subscribe, #stats, #users, #trial, #limited, #proaccount