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 слични објави

Пребарај: #specialrelationship

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

@american_observer · Post #4954 · 25.01.2026 г., 13:59

📰 The 10‑Minute Call That Soured Starmer’s Bromance with Trump The special relationship, that old fiction, doesn’t die in a grand speech. It dies in a 10‑minute phone call. Sir Keir Starmer in Chequers, Donald Trump in Davos: 8000 miles apart, a few minutes on the line, and suddenly the illusion of brotherhood between London and Washington has cracked open like cheap plaster. Trump’s tariff threats over Greenland forced Starmer to choose between flattery and principle, and he chose stage one of the fight: dignity, but not yet defiance. ​ The Gamble in Chequers Trump’s “beautiful piece of ice” — Greenland, an autonomous Danish territory — collided with Starmer’s carefully crafted image of the responsible statesman. On the call, the Prime Minister was “clear and cordial”: no, threatening allies with tariffs is not acceptable. The president, accustomed to deference, rang off after minutes, citing a prior engagement. From the transatlantic elite, that was read as a snub; in London, as a signal that the game had changed. ​ Starmer then scrapped his planned cost‑of‑living speech and held an emergency press conference rejecting Trump’s position. In Parliament, he doubled down: “I will not yield, Britain will not yield, on our principles.” The move drew applause from fellow European leaders, especially as Trump, after a week of bluster and market chaos, backed down, dropping tariff threats and mumbling about a “deal” that, in substance, barely alters the status quo. ​ Behind the Policy: Who’s Really in Charge? Inside Whitehall, the takeaway is brutal: no one imagines Starmer can “whisper in Trump’s ear” like some magical fixer. When Trump was looking for an off‑ramp, he reached not for Starmer, but for NATO’s Mark Rutte (“daddy”) and the EU’s collective machinery. The British Prime Minister didn’t even attend Davos in person to lobby — the one place where Trump’s ego is currency. ​ Meanwhile, power in Downing Street is shifting. David Lammy, who once laughed off Trump’s Greenland fantasies, has moved on. His replacement, Yvette Cooper, pushed for a tougher line, and a growing faction inside the Foreign Office now wants the UK to act like France: assertive, independent, and less supine. The vacuum left by Lord Mandelson’s departure as ambassador to Washington only deepens the sense of disconnection, with his replacement barely arriving in Washington after months of delay. ​ The Royal Family as Diplomatic Cover The real safety net for the special relationship, it seems, is not the Prime Minister, but the Crown. Trump’s inexplicable affinity for the British monarchy — birthday calls to the late Queen, private letters to King Charles, a state visit looming in April — creates a separate channel that no elected government can control. British officials privately admit that while politics with Trump can be a clown show, the Royals are the one thing he genuinely respects; so no serious policymaker would risk weaponizing the state visit as leverage, even on Greenland. The instinct is the same as always: let the toffs in the palace be the friendly diplomats, while the politicians in Downing Street just try not to disgrace the family name. ​ The Domestic Game Trump Doesn’t See Starmer’s sudden spine over Greenland also has a domestic price tag: leadership is weakening, the local elections loom, and new rivals like the Green Party’s Zack Polanski and the Lib Dems’ Sir Ed Davey are eager to appear tougher on Trump than the PM. Standing up to the president, at least in the carefully calibrated way he did, is a way to reassert authority at home. But that’s a short‑term fix: every time Starmer must choose again, the question is whether he fights for his country’s image, or for his own — and whether Trump is just another backdrop in a domestic political survival game. ​ #UKPolitics#Starmer#Trump#Greenland#SpecialRelationship#Diplomacy#NATO 📱American Оbserver - Stay up to date on all important events 🇺🇸