TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #22 · 19 јан.

Заметка начинающим, которые часто сталкиваются с подобной непоняткой. Ситуация следующая, есть список файлов: names = [ 'image.bmp', 'second.txt.bkp', 'data.db', '.config.cfg', 'file.ext.bkp' ] И мы хотим убрать у них окончание ".bkp". Не знаю зачем, пример довольно надуманный) Но суть он показывает, а это главное. Те, кто еще не очень знаком с библиотекой os.path или pathlib, вероятно решат обработать имена как строки. И тут вполне подойдет метод строки strip(). Что делает этот метод? Он отрезает указанные символы по обеим сторонам строки. Если ничего не указать, то убирает невидимые символы (пробелы, табуляции и переносы строк). В нашем случае будет выглядеть вот так: >>> name.strip('.bkp') То есть просим удалить строку '.bkp' по краям имени файла, если таковая есть. Можно применить аналогичный метод rstrip(), чтобы отрезать только справа, но для этого примера используем обычный. >>> for name in names: >>> print(name.strip('.bkp')) image.bm second.txt data.d config.cfg file.ext Хм, что-то не то с нашими именами! Что случилось??? Видим нежелательное переименование в именах, где и близко не было указанной строки '.bkp' А дело всё в том, что данный метод ищет не указанную строку, а указанные символы, и не важно в каком порядке. Для метода strip() строка '.bkp' это не паттерн для поискаа список символов. Потому он отрезал симовол 'p' от '.bmp' и удалил точку из файла '.config.cfg'. Как тогда правильно заменить именно паттерн? Для начинающего можно посоветовать метод строки replace(), который как раз использует для замены указанную строку целиком. В нашем примере заменим её на пустую строку. >>> for name in names: >>> print(name.replace('.bkp', '')) image.bmp second.txt data.db .config.cfg file.ext Уже лучше, но помните, это лишь пример про strip(). Для работы с именами файлов есть способы и более "правильные", дающие однозначно верный результат. Я взял файлы только в качестве примера. Даже replase() тут может сделать не то что ожидаем. Просто впредь будьте внимательны с этим strip(). #basic

Hashtags

Резултати

Пронајдени 4 слични објави

Пребарај: #technicaldetails

当前筛选 #technicaldetails清除筛选
Luckydonalds Bots: Development/Status

@luckydonaldsbots · Post #145 · 22.07.2018 г., 04:19

Why are there 5 buttons now? Technical details time (6am local) In order to switch to private chat we have to let the user click on a t.me/RulesRulesBot link with a start parameter. However, Telegram requires the first button to be a GameCallback button. It cannot be a normal url button. When that button is clicked, the bot gets an incoming update, which it can act upon. One way is to send a url to navigate to (open the game). I tried using the t.me start link there, but that doesn't work smoothly across all Telegram clients. Here is a summary: - Telegram Mac works without problem - Telegram on iOS works, but briefly shows a frame of the Telegram homepage before jumping to the chat - Telegram Android opens the Telegram website, and nothing happens - Telegram Desktop doesn't work at all, showing an error about the user not being found. Therefore I choose to disable the button showing the user an message he should use one of the plenty other buttons. Long answer short, with more buttons, the wrong one gets smaller, as does the chance to hit it. #TechnicalDetails

Luckydonalds Bots: Development/Status

@luckydonaldsbots · Post #188 · 24.02.2019 г., 01:05

If you docker refuses to start and sudo service docker status is showing logs like this: Feb 24 01:30:06 hostname dockerd[19544]: time="2019-02-24T01:30:06.718823877+01:00" level=error msg="stream copy error: reading from a closed fifo" It might be that /var/run/docker.sock is a mount in one of your containers. Therefore if that doesn't exist - and only shortly - it will be created as a folder, thus making it impossible for docker to start. Fix it with sudo rmdir /var/run/docker.sock, and sudo service docker start. #TechnicalDetails#downtime#in_progress

Luckydonalds Bots: Development/Status

@luckydonaldsbots · Post #166 · 25.11.2018 г., 14:47

Updated @YATubeBot to be more clear of errors related to upload size. Will now handle file size related upload errors more transparent, telling you exactly what's going on, instead of just stopping sending any updates after "Uploading...". Now it will check file size before uploading, and also handle rare errors raised (in an unspecified way) by telegram. Technical background: The telegram API returns a HTML error message instead of the usual json response, which of course isn't mentioned anywere in the API documentation. This broke pytgbot, the library used to interact with the API. The package was fixed to be able to handle that. Now also provides the file size of the file to upload in an easy accessable way, so that the upload size can be checked before uploading. #update#YATube#pytgbot#TechnicalDetails

Luckydonalds Bots: Development/Status

@luckydonaldsbots · Post #161 · 21.10.2018 г., 08:02

Downtime yesterday TL;DR: After a restart, not all services got back online. Turns out, when I refreshed my docker-machine certificates, which it uses to securely talk to my remote server, it had to restart docker. Those certificates work for 3 years and have to be recreated if they expire. (Wow, I'm working with telegram bots for a while now, huh?) Somehow some services (e.g. @YATubeBot, @ForwardWhitelistBot) didn't restart, and the @StickerTagBot even reverted to a old version from last year. Anyway I redeployed the correct version. If something else isn't running how it used to, please contact me personally @luckydonald. #downtime#TechnicalDetails#YATube#ForwardWhitelist#StickerTag