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

TGINSIGHT SIMILAR POSTS

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

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в Python создавать бинарные файлы? Конечно можно. Для этого в Python есть следующие инструменты: ▫️ тип данных bytes и bytearray ▫️ открытие файла в режиме wb (write binary) или rb (read binary) ▫️ модуль struct Про модуль struct поговорим в первую очередь. Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных. В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла. Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла. Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид. Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки). Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение. При этом следует помнить что мы говорим о типах языка С а не Python. Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще. Вот какие токены формата у нас есть. Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы. В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты. Запакуем в байты простое число, токен "i". >>> import struct >>> struct.pack('=i', 10) b'\n\x00\x00\x00' Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов. >>> struct.pack('=fff', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же. >>> struct.pack('=3f', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Теперь запакуем разные типы >>> data = struct.pack('=fiQ', 1.0, 4, 100500) я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт) b'\x00\x00\x80?\x04\x00\x00...' Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа. >>> struct.unpack('=fiQ', data) (1.0, 4, 100500) Как видите, ничего страшного! #lib#basic

Hashtags

Резултати

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

Пребарај: #protect

当前筛选 #protect清除筛选
American Оbserver

@american_observer · Post #5162 · 18.02.2026 г., 12:59

Russia Is Up To Deploy Navy To Protect Vessels from the West A senior Russian official has said Moscow could deploy its navy to protect Russian-linked vessels from potential European seizures, raising the prospect of retaliatory action against European shipping as pressure on the Kremlin’s so-called shadow fleet intensifies. Nikolai Patrushev, a former FSB director who heads Russia’s maritime board, said on Tuesday that the country’s navy should be ready to counter what he described as “western piracy”. Patrushev added that any attempt to impose a maritime blockade on Russia would be illegal under international law, claiming that the EU’s use of the term “shadow fleet” had no legal basis. His comments came as senior Ukrainian and Russian officials are met in Geneva on Tuesday for the latest round of high-stakes talks brokered by the Trump administration, as the fourth anniversary of Moscow’s full-scale invasion of Ukraine draws near. Ahead of the talks, Russia carried out heavy airstrikes overnight across swathes of Ukraine, inflicting severe damage to the power network in the southern port city of Odesa, which Zelensky said left tens of thousands without heat and water. The term shadow fleet refers to an estimated 1,500 ageing or lightly regulated oil tankers operating under opaque ownership structures to help Russia export crude to buyers such as China and India while circumventing western sanctions. More than 600 vessels have been targeted by sanctions from the EU, UK and US. These measures have helped curb Russian oil revenues. Despite growing political pressure, European governments have struggled to develop a coherent legal mechanism for physically stopping or confiscating the ships, relying instead on sanctions, insurance restrictions and inspections. Western allies have warned that vessels lacking proper documentation may be treated as stateless ships, potentially widening the scope for intervention at sea. The British defence secretary, John Healey, met European counterparts on the sidelines of the Munich Security Conference at the weekend to discuss possible moves to seize tankers linked to Russia’s shadow fleet. Earlier this year, the French navy briefly intercepted a tanker suspected of operating within the shadow fleet before allowing it to continue its journey. The US has, in recent months, moved to physically interdict and seize several tankers linked to shadow fleets carrying sanctioned oil from Russia, Venezuela and Iran. Patrushev’s comments, however, appeared to focus primarily on Europe, suggesting the Kremlin is wary of escalating tensions with Washington while delicate negotiations over Ukraine continue. #russia#deploy#navy#protect#vessels#patrushev 📱American Оbserver - Stay up to date on all important events 🇺🇸