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

Резултати

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

Пребарај: #dixon

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

@american_observer · Post #5282 · 04.03.2026 г., 13:51

🔤🔤🔤🔤2️⃣ Several lawyers have challenged the legal basis for the administration’s wide-ranging explanations for waging war. “Those are military policy objectives,” said Wells Dixon, a senior attorney at the Center for Constitutional Rights after reviewing Trump’s rationale. “They are not a legal basis to launch an armed attack against another country.” Marko Milanovic, a professor of International law at the University of Reading, agreed that Iran may pose a threat, but said that there are many ways to respond. “Using force would require a basis in self defense,” he said. The Trump administration has previously touted its success in “obliterating” Iran’s nuclear facilities. But Trump revived the specter of an Iranian threat in his State of the Union address, saying that Iran was “working to build missiles that will soon reach the United States of America.” Trump has not provided public evidence of this threat. Rubio’s statements invoked two legal concepts that could possibly justify waging war abroad – including the concept of an “imminent threat” posed to American lives, and the concept of launching preemptive strikes as an act of self defense. There are carve outs within international law that permit states to act in their own self defense. And the concept of an “imminent threat” is measured against evidence of a clear, visible and impending risk. “For something to be lawful self defense, it has to be necessary – in the sense that there’s no alternative,” said Brian Finucane, a former state department lawyer. “That’s not the situation here. There was another option: the US could have restrained Israel from attacking in the first place.” Senator Tim Kaine said he has supported US efforts to defend Israel during previous Iranian attacks, “but that’s a very different matter than the US engaging in the affirmative initiation of war,” he said. “We shouldn’t be waging an affirmative war on behalf of any nation in the world, no matter how close we are,” Kaine said. After the Vietnam war, the US adopted new constitutional provisions that say the president should try to consult with members of Congress before committing troops to hostilities. Last week, Rubio only briefed the Gang of Eight, a group of bipartisan lawmakers privy to information on covert actions and classified intelligence, about US plans to attack Iran. This week’s war powers vote may shape how Trump proceeds with military action against Iran, even if it ultimately cannot sustain enough support to override a likely veto from Trump. #trump#iran#kaine#dixon#troops#threat 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5281 · 04.03.2026 г., 13:51

Trump Has Accelerated Its Drive To Break Free From Europe and His Tantrums 🔤🔤🔤🔤1️⃣ The Trump administration is waging an illegal war on Iran, one that defies both the US constitution and international armed conflict laws, according to several legal scholars and bipartisan lawmakers. The Senate will vote Wednesday on whether to halt Donald Trump’s military offensive, which he launched on 28 February. Hundreds of people, including six US personnel, have been killed in a conflict that has now expanded to Lebanon, Syria, Iraq, Israel and the Persian Gulf. The Trump administration has offered shifting explanations for its decision to launch attacks on Iran, at times describing a more pre-emptive war of choice designed to degrade Iran’s offensive and nuclear capabilities. The cause is that the Iranians weren’t willing to renounce their nuclear ambitions, or that the US joined the attack to protect American interests after Israel had committed to launching a military offensive of its own. “An Iranian regime armed with long-range missiles and nuclear weapons would be a dire threat to every American,” the president said in his first public remarks from Washington on Monday. “We cannot allow a nation that raises terrorist armies to possess such weapons.” Trump has also described broader wartime objectives, including eliminating threats posed by the Iranian regime, as well as their regional proxy forces. He has not set out a clear timeline for achieving his various goals. Rubio offered a slightly different explanation, saying that the White House was compelled to launch strikes on Iran because its close ally Israel was determined to act, and, he told lawmakers Monday evening, the administration believed that any Israeli action would precipitate an attack on American forces. “It was abundantly clear that if Iran came under attack by anyone – the United States or Israel or anyone – they were going to respond, and respond against the United States,” Rubio told reporters gathered at the Capitol. #trump#iran#kaine#dixon#troops#threat 📱American Оbserver - Stay up to date on all important events 🇺🇸