Как разделить строку с 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
🌎 Deep in southeastern Iran, the mysterious Kaluts desert features gigantic, wind-carved sand formations called “yardangs.” These natural sculptures stretch for kilometers, shaped by centuries of relentless wind erosion. ✨
#geology⚡#desert⚡#landscapes
👉subscribe Interesting Planet
🌎 Powerful enough to move mountains, glaciers shaped entire continents. As they advanced, their slow, grinding ice carved out valleys, lakes, and fjords still visible today. ✨
#geology⚡#glaciers⚡#landscapes
👉subscribe Interesting Planet
🌎 Southern China’s Stone Forest, or Shilin, is a dramatic landscape of towering limestone pillars shaped by both natural erosion and centuries of quarrying. Human mining over the last thousand years has altered parts of this ancient karst region, creating new rock formations and open spaces alongside original spires. ✨
#geology⚡#humanimpact⚡#landscapes
👉subscribe Interesting Planet
👉more Channels
🌍 The Rice Terraces of Yuanyang in China were carved into steep mountains over centuries. These living heritage sites are so vast they create their own microclimate and reflect the region's cultural history. ✨
#heritage⚡#landscapes⚡#agriculture⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The geographic shell of the Earth includes plateaus, plains, and mountain ranges, creating a patchwork that determines where rivers flow and where different climates form. ✨
#landforms⚡#climate⚡#landscapes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 In Japan, centuries-old forest areas called satoyama are shaped by human care for farming, wood, and water, blending wild nature and villages into landscapes rich in biodiversity and tradition. ✨
#interaction⚡#landscapes⚡#biodiversity⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Some arid desert landscapes feature ancient, dried-up riverbeds called wadis that can flood suddenly after rare rains, quickly turning from bare channels to rushing streams in a matter of hours. ✨
#desert⚡#arid⚡#landscapes⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In Indonesia, ancient forests and rice terraces share land with villages, blending wild and human-shaped environments. This mix supports rare wildlife while feeding local communities. ✨
#interaction⚡#landscapes⚡#sustainability⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In China's southern hills, vast terraces transform mountains into rice fields. These hand-carved steps let farmers grow crops high above valleys, creating some of the world’s most scenic farmland. ✨
#agriculture⚡#landscapes⚡#rice⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 Italy’s Cinque Terre is a World Heritage Site where human-built terraced vineyards cling to steep cliffs beside the sea. Centuries of farming have shaped this landscape into a living cultural mosaic. ✨
#heritage⚡#landscapes⚡#vineyards⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 England’s Lake District is a UNESCO World Heritage Site where centuries of sheep farming shaped rolling hills and stone walls, blending natural scenery with a rich cultural landscape. ✨
#heritage⚡#landscapes⚡#UNESCO⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍