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

Резултати

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

Пребарај: #blockading

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

@american_observer · Post #5606 · 13.04.2026 г., 14:59

🔤🔤🔤🔤2️⃣ The US and Iranian delegations left Pakistan soon after the talks ended. Vance said he spoke with Trump at least half a dozen times during the talks, held during a 14-day ceasefire announced by the US, Israel and Iran overnight on 7 and 8 April. “We need to see an affirmative commitment that [Iran] will not seek a nuclear weapon, and they will not seek the tools that would enable them to quickly achieve a nuclear weapon,” Vance said. “That is the core goal of the president of the United States, and that’s what we’ve tried to achieve through these negotiations.” Mohammad Ghalibaf, the speaker of the Iranian parliament, who led Tehran’s negotiators, said he and his colleagues had offered “constructive initiatives” while the US had been “unable to gain the trust of the Iranian delegation in this round of negotiations”. Iran’s semi-official Tasnim news agency said “excessive” US demands had hindered reaching an agreement, and the foreign ministry said more time was needed. “Naturally, from the beginning we should not have expected to reach an agreement in a single session,” the ministry’s spokesperson Esmail Baghaei said, according to the state broadcaster IRIB. Pakistani mediators called on the US and Iran to refrain from renewing hostilities and said they would try to arrange a fresh round of talks. “It is imperative that the parties continue to uphold their commitment to the ceasefire,” said Pakistan’s foreign minister, Ishaq Dar. Vance was accompanied by the US special envoy Steve Witkoff and Trump’s son-in-law Kushner. They met Ghalibaf and the Iranian foreign minister, Abbas Araghchi, for several negotiating sessions at the Serena hotel in Islamabad, with Pakistan’s army chief, Asim Munir, also present. Iran’s delegation arrived on Friday dressed in black in mourning for the late supreme leader Ayatollah Ali Khamenei and others killed in the war. They carried shoes and bags of children killed during the bombing of a school next to a military compound, the Iranian government said. A Pakistani source said the discussions, the highest-level direct contact between the US and Iran since 1979, were unpredictable in tone. “There were mood swings from the two sides, and the temperature went up and down during the meeting,” a Pakistani source said after the first round. Trump said: “The only thing left, really, is their water, which would be very devastating to hit. I would hate to do it, but it’s their water, their desalinisation plans, their electric generating plants, which are very easy to hit.” The president was asked if gas and oil prices might be lower by the US midterms in November, an indication that attacking Iran was not an economic mistake. Prices “could be the same or maybe a little bit higher,” a non-committal Trump replied. At the Vatican, Pope Leo XIV called for a ceasefire after his Sunday prayers and said he felt “closer than ever” to Lebanon’s people. #trump#iran#strait#hormuz#vance#blockading 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5605 · 13.04.2026 г., 13:59

The Negotiations With Iran Went Belly Up. Will the War Re-Start? 🔤🔤🔤🔤1️⃣ Trump has said the US will begin blockading the strait of Hormuz in an attempt to take control of the strategic waterway from Iran in the aftermath of failed peace negotiations between the countries in Pakistan. The US president also threatened to bomb Iran’s water treatment facilities, power plants and bridges, repeating an earlier threat, if Tehran does not agree to abandon its nuclear weapons programme, the key sticking point between the two sides. Trump’s surprise announcement of a blockade came after face-to-face peace negotiations between the US and Iran in Islamabad that lasted 21 hours collapsed on Sunday morning. Vance said Iran had refused to give up the possibility of developing nuclear weapons, while the Iranian delegates said Washington needed to do more to win their trust. Risking another increase in oil prices, Trump said he had instructed the US navy to begin “blockading any and all ships trying to enter, or leave, the Strait of Hormuz,” and he accused Iran of extortion with its own scheme of charging tolls to tankers. Iran’s Revolutionary Guards responded by declaring that if any warships approached the strait to enforce a blockade – usually considered an act of war – it would be considered a breach of the current ceasefire and would be dealt with strongly. They insisted the strait remained under Iranian control. Two US destroyers crossed and recrossed the strait without incident on Saturday, although Iranian media said they were threatened as they left. The US military said it was the start of a mine-clearance mission. Trump said US warships would “seek and interdict every vessel” that had paid Iran since the start of the conflict and begin de-mining the central section of the strait, previously declared a “hazardous area” by Tehran, although it is unclear how many mines have been laid. About 100 tankers have transited the strait since the US and Israel started bombing Iran, paying up to $2m each time for passage. Many were bound for China and India, carrying Iranian oil products, and chasing them down could complicate relations between the US and the importing nations. #trump#iran#strait#hormuz#vance#blockading 📱American Оbserver - Stay up to date on all important events 🇺🇸