Python + bash
Если вам часто требуется запускать shell команды из Python-кода, какой способ вы используете?
Самый низкоуровневый это функция os.system(), либо os.popen(). Рекомендованный способ это subprocess.call(). Но это всё еще достаточно неудобно.
Советую обратить своё внимание на очень крутую библиотеку sh.
Что она умеет?
🔸 удобный синтаксис вызова команд как функций
# os
import os
os.system("tar cvf demo.tar ~/")
# subprocess
import subprocess
subprocess.call(['tar', 'cvf', 'demo.tar', '~/'])
# sh
import sh
sh.tar('cvf', 'demo.tar', "~/")
🔸 простое создание функции-алиаса для длинной команды
fn = sh.lsof.bake('-i', '-P', '-n')
output = sh.grep(fn(), 'LISTEN')
в этом примере также задействован пайпинг
🔸 удобный вызов команд от sudo
with sh.contrib.sudo:
print(ls("/root"))
Такой запрос спросит пароль. Чтобы это работало нужно соответствующим способом настроить юзера.
А вот вариант с вводом пароля через код.
password = "secret"
sudo = sh.sudo.bake("-S", _in=password+"\n")
print(sudo.ls("/root"))
Это не все фишки. Больше интересных примеров смотрите в документации.
Специально для Windows💀 юзеров
#libs#linux
Dushanbe is a bright, sunny ☀️ and unique city that will always remain in your heart. Beautiful Dushanbe has many interesting sights and places where you can spend your time. The flagpole with the flag of Tajikistan 🇹🇯 and the National Museum of Tajikistan are obligatory for visiting. Do not forget to visit the Istiqlol Complex and take a walk in Rudaki Park. 🌳 In addition, you will certainly be pleased with the performances of the Tajik State Academic Opera and Ballet 🩰 Theater. On a hot summer day, you can hide in Aquaparks 🏊 and spend the whole day there. And mark the Mehrgon market in your route map. The aroma of hot bread, spices, as well as fresh vegetables and fruits 🍉 will make you come back here again. Welcome to Dushanbe!
#dushanbe#somonair
RT @Anahita_SD: The Pashtuns, a new book was published in #Dushanbe this year. The book is written in Russian by Homid Saidov who worked in Afghanistan from 1978 till 1989 #Afghanistanhttps://t.co/oml7vL2uS6
— FJ (@Natsecjeff) Apr 27, 2022
Dushanbe is a beautiful, cozy, green city full of colors and wonderful people. It is a garden city dotted with shady alleys and parks with fountains. Museums of the city will tell you its history, and numerous teahouses will serve delicious food. We can talk a lot about Dushanbe, but it's better to come and see everything for yourself. Welcome to sunny Dushanbe!
✈️
Душанбе - это волшебный, уютный, зелёный город, полный красок и замечательных людей. Это город-сад, усеянный тенистыми аллеями и парками с фонтанами. Музеи города расскажут вам его историю, а многочисленные чайханы вкусно накормят. О Душанбе можно говорить много, но лучше приехать и увидеть всё самому. Добро пожаловать в солнечный Душанбе!
#dushanbe#душанбе
Starting from February 3, 2025, flights from Dushanbe to Tehran will operate at updated times, providing passengers with even more convenience when planning their travel. Thus, flights will be carried out not in the evening, as was the case before, but in the daytime. Departure time from Dushanbe is at 10:00, from Tehran – at 12:50 local time.
In addition, starting from March 5, 2025, Somon Air will introduce an additional frequency of flights on this route on Wednesdays. This will allow passengers to travel more frequently between Tajikistan and Iran. Departure from Dushanbe is at 14:00, from Tehran – at 16:50 local time. Travel time from Dushanbe to Tehran is 2 hours 50 minutes, in the opposite direction - 2 hours 30 minutes.
Thus, starting from March 5, Somon Air will operate flights to Tehran twice a week - on Mondays and Wednesdays. The flights will be operated on Boeing 737-800 and Boeing 737-900 aircraft.
#somonair#dushanbe#tehran
Somon Air launched a new route - from Dushanbe to #Munich (Germany) and return. According to schedule, the flights are to be operated once a week, every Monday.
Departure from Dushanbe at 06:00, arrival in Munich at 09:30 local time. Departure from Munich at 11:30, arrival at 20:30 local time. All flights are to be operated with Boeing 737-900.
For more details, please visit the airline's website, or contact sales offices and Call-center.
#dushanbe#munich#somonair
Do you miss the Sun? ☀️ There is a lot of it in Dushanbe, spring is in full swing here.
Head to the capital city of Tajikistan and catch some bright spring vibes! Welcome to Dushanbe!
✈️
Соскучились по солнцу? ☀️ В Душанбе его много, весна здесь в самом разгаре.
Отправляйтесь в столицу Таджикистана и окунитесь в атмосферу яркой весны! Добро пожаловать в Душанбе!
#dushanbe#tajikistan#душанбе#таджикистан
Dear passengers!
If you plan to travel to Munich, kindly note the following information. From February 4, 2023, the flight schedule on the Dushanbe-Munich-Dushanbe route is changing and operates on Saturdays departing at Dushanbe at 01:40 local time, and at Munich at 17:05 local time. The new schedule will create more flexibility for passengers, especially transit passengers, providing more opportunities for connecting flights.
✈️
Уважаемые пассажиры!
С 4 февраля 2023 года меняется расписание полётов по маршруту Душанбе-Мюнхен-Душанбе. Согласно новому расписанию рейсы будут выполняться по субботам. Вылет из Душанбе – в 01:40 по местному времени, из Мюнхена – в 17:05 по местному времени. Новое расписание создаст больше удобств для пассажиров, в особенности транзитных и даст им возможность выбора более удобных стыковочных рейсов.
#dushanbe#munich#душанбе#мюнхен
Душанбе - #Мюнхен. Ҳар ҳафта, рӯзҳои душанбе. Олмонро барои худ кашф намоед.
✈️
Душанбе – Мюнхен. Раз в неделю, по понедельникам. Откройте для себя Германию!
✈️
Dushanbe – Munich. Once a week, on Mondays. Discover Germany.
#душанбе#мюнхен#сомонэйр#dushanbe#munich#somonair
Мы открыли прямой авиарейс из Душанбе в Тбилиси. Первый рейс состоялся 22 мая. Полёты будут выполняться раз в неделю, по средам. За более подробной информацией и по вопросам приобретения тура просим обращаться по телефонам: 1133, +992 88 877 50 05.
✈️
We opened a direct flight from Dushanbe to Tbilisi. The first flight took place on May, 22. Flights will be operated once a week, on Wednesdays. For getting more information and purchasing a tour, please contact: 1133, +992 88 877 50 05.
✈️
Мо хатсайри мустақими Душанбе – Тбилисиро роҳандозӣ намудем. Парвози нахустин санаи 22-юми май сурат гирифт ва минбаъд парвозҳо ҳафтае як маротиба, рӯзҳои чоршанбе анҷом дода мешаванд. Барои гирифтани маълумоти бештар ва хариди бастаҳои сайёҳӣ хоҳишмандон метавонанд тариқи телефонҳои 1133, +992 88 877 50 05 тамос бигиранд.
#сомонэйр#душанбе#тбилиси#somonair#dushanbe#tbilisi
❗️Уже завтра в Душанбе стартует Dushanbe Invest Forum 2025!
С 14 по 16 октября столица Таджикистана станет точкой притяжения для инвесторов, экспертов и предпринимателей со всего мира.
Первый день форума откроется пленарным заседанием и панельными сессиями по ключевым темам — зелёные инвестиции, чистая энергетика, ESG, цифровизация и искусственный интеллект.
Форум станет платформой для диалога, сотрудничества и новых международных проектов.
🔗 Регистрация: dushanbeinvest.com
#DushanbeInvest2025#DIIF2025#TajikistanInvestments#BusinessForum#Dushanbe
Подпишись: ✅Telegram
Shavkat Mirziyoyev Dushanbeda o‘tgan “Markaziy Osiyo – Rossiya” sammitida mintaqa barqarorligi Rossiya bilan yaqin hamkorlikka bog‘liq ekanini ta’kidladi.
https://yep.uz/uz/2025/10/markaziy-osiyo-rossiya-hamkorlik-mirziyoyev/
#Mirziyoyev#Rossiya#MarkaziyOsiyo#O‘zbekiston #Hamkorlik#Sammit#Dushanbe#Siyosat