Как разделить строку с shell-командой на отдельные аргументы в виде списка?
Если сделать просто сплит по пробелу то получим то что надо, кроме случаев со вставками текста с пробелами. Например так:
>>> '-arg "I Am Groot"'.split(' ')
['-arg', '"I', 'Am', 'Groot"']
Чтобы учитывать текст в кавычках как единый аргумент можно воспользоваться функцией shlex.split()
Кто читает мой канал давно, уже в курсе.
А что делать, если нужно обратное действие? Объединить аргументы из списка в строку и при этом добавить кавычки в аргумент с пробелами.
Конечно, если вы используете subprocess то он сам всё разрулит. Но если вам нужна именно команда одной строкой, то можно воспользоваться готовой функцией в том же subprocess.
>>> from subprocess import list2cmdline
>>> list2cmdline(['-arg', 'I Am Groot'])
'-arg "I Am Groot"'
Он также позаботится об экранировании уже имеющихся кавычек
>>> list2cmdline(['-arg', 'I Am "Groot"'])
'-arg "I Am \"Groot\""'
А вот так он может "схлопнуть" в команду JSON
>>> list2cmdline(['--json', json.dumps({'key': 'value'})])
'--json "{\"key\": \"value\"}"'
_______________
Возможно кто-то спросит, а зачем соединять аргументы в строку если subprocess сам это сделает а os.system не наш путь?
Мне как-то потребовалось отправлять команду на удалённое выполнение и в API поддерживалось указание команды только строкой. Так что всякое бывает)
#libs#basic
Oil Market Balance May Return by April
An increase in traffic through the Strait of Hormuz by 5–6 tankers daily could restore market balance. Despite the London insurance market halt, up to 42% of the fleet under Liberia, Marshall Islands, Malta, and Bahamas flags are shifting to Chinese and Indian state guarantees. Panama and Singapore’s flexible fleets adapt faster, while Iran and Hong Kong’s “shadow fleet” bypass sanctions and remain active.
#oil#market#sanctions#Russia#maritimetraffic
The main news of Russia and the world ishere.
🚀 Increase in Ship Traffic Through Strait of Hormuz Observed
On April 10, the number of ships passing through the Strait of Hormuz increased to nine, according to data from shipping intelligence company Kpler. According to BlockBeats, this marks a rise from the previous day's count of five vessels, although it remains below the broader normalized levels.
#Shipping#StraitOfHormuz#MaritimeTraffic#Kpler#BlockBeats
🚀 Strait of Hormuz Traffic Halts Following U.S. Maritime Blockade
All maritime traffic through the Strait of Hormuz has reportedly ceased after U.S. President Donald Trump declared a maritime blockade via social media. According to NS3.AI, information from British sources, as reported by CCTV News, indicated that the blockade had been in place for several hours. While traffic was still feasible on the 12th, at least two vessels attempting to exit the strait reversed course. Tanker traffic had seen a slight uptick on the 11th before declining on the 12th.
#StraitOfHormuz#MaritimeBlockade#USPresident#DonaldTrump#TankerTraffic#CCTVNews#NS3AI#MaritimeTraffic
🚀 Iran Considers Bitcoin Toll for Ships in Strait of Hormuz
Iran is contemplating a new toll system for ships passing through the Strait of Hormuz, potentially requiring a $1-per-barrel fee payable in Bitcoin. According to NS3.AI, Hamid Hosseini, spokesperson for Iran’s Oil, Gas, and Petrochemical Products Exporters’ Union, indicated that this move could significantly impact maritime traffic. Arkham, a maritime analytics firm, estimates that a typical cargo ship carrying around 3 million barrels would face a payment of approximately $3 million in Bitcoin. Martin Kelly, head of advisory at maritime intelligence group EOS Risk, noted that this regulation could reduce the number of ships allowed to pass through the strait to 10–15 per day, a sharp decrease from the current average of about 135 ships.
#Iran#Bitcoin#Toll#StraitOfHormuz#Shipping#MaritimeTraffic#Oil#Cryptocurrency#Petrochemical#MaritimeRegulation#BTC
🚀 WTI Crude Oil Rises 10% Amid U.S.-Iran Peace Talks Stalemate
WTI crude oil experienced a significant intraday increase of 10%, reaching $105.33 per barrel, following the conclusion of the initial round of U.S.-Iran peace talks in Islamabad, which ended without an agreement. According to NS3.AI, the U.S. Central Command announced plans to block all maritime traffic to and from Iranian ports starting at 2:00 p.m. UTC on April 13. The U.S. military clarified that vessels traveling through the Strait of Hormuz to non-Iranian ports will not encounter any restrictions.
#WTI#CrudeOil#USIranPeaceTalks#MaritimeTraffic#Iran#StraitOfHormuz#USTechnology#NS3AI#CentralCommand#OilPrices