Мы любим консольные приложения, но как много способов мы знаем, чтобы оформить вывод в консоль кроме простого print? Я уже рассказывал на своем телеграм-канале про TQDM для красивых прогресс-баров. Теперь расскажу, как делать красивые таблицы.

Рекомендую библиотеку PrettyTable (


pip install prettytable

Простой пример. Зададим сначала поля, которые отобразятся в заголовке, а потом добавим строчки.

from prettytable import PrettyTable

x = PrettyTable()

# зададим названия полей в заголовках
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

# добавим строки данных
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print(x) # проще простого!

Получим на экране:

| City name | Area | Population | Annual Rainfall |
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |

Того же эффекта можно достичь, если добавлять данных по столбцам (иногда так удобнее).

x = PrettyTable()

x.add_column("City name", 
x.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
x.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 
x.add_column("Annual Rainfall",[600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 


Даже если вы не фанат консоли, то иногда нужно сохранить отчет о работе вашей программы в текстовый файл. Туда мы тоже можем добавить и нашу таблицу.

with open('1.txt', 'w') as f:

Если мы работаем с базой данных, например Sqlite, то можно печатать результаты ваших запросов красивыми таблицами вот так:

import sqlite3
from prettytable import from_cursor

# тут вы загружаете вашу БД и делаете запрос, какой надо.
connection = sqlite3.connect("mydb.db")
cursor = connection.cursor()
cursor.execute("SELECT field1, field2, field3 FROM my_table")
mytable = from_cursor(cursor)


Параметры таблицы можно кастомизировать, меняя практически все, что придет в голову. Также вывод таблицы можно сортировать, выделять нужные колонки и диапазоны рядов. Читайте официальную документацию или пишите комментарии.

Специально для канала PyWay.

The Longing

I’ve seen many men wandering
all strong and brave and keen
Seen them growing into rulers
but I long for the sea
Heard a ship came from North
to our harbour for a day
and before misfortune knows
I’ll be on my way

I’m all set to veer away
and I’m all set to go astray
All burdens I will leave ashore
to find what I’ve been longing for

Don‘t tell anyone
that this night I’ll be gone
Greeting the eternal blue
right at the break of dawn
Sailing t‘wards the unknown
with my crew on the sea
And the day that I return
a hero I shall be

I’m all set to veer away
and I’m all set to go astray
All burdens I will leave ashore
to find what I’ve been longing for

© Storm Seeker

MacOS remarkable feature

Today I discovered one more remarkable feature of Mac OS. I have two different SSDs each have a Mac OS installation (the old one is El Captain and the new one is Sierra). I accidentally found out that I can run applications installed in the old system from the new system. They are listed in the Spotlight Search.

The Weather’s gift

I asked the Nature for a little gift for us by the day we will have set off for our Thailand trip. And she bestowed us with this kind of weather. It’s freezing cold and snowing outside. Winter came back to the city. It will make a tremendous contrast between here and there. We’ll take off in the middle of the winter around and land in the tropical paradise.

The world is a mirror.

The world is just a mirror. It reflects that you think about it. If you think that the worlds is happy place where you can get everything easy then the world will be such place. But if you think that the world is unhappy and tough and only ones who were born lucky enough will live happily and wealthily then you doomed to be a loser.

Your attitude to the world surrounding you is the real matter. Change your attitude from negative to positive and you’ll be surprised how the world will change itself according your attitude.

Checklist: motorbike rental

There is just a little memo for me for tomorrow.

The actions you need to do when you rent a motorbike:

  1. Choose a motorbike by its engine capacity. You don’t need 125 cm2 or more. 50-90  cm2 will be enough.
  2. Ask the staff to show you how to insert the key, how to start the bike, how to open the trunk, how to pull out the stand and so on.
  3. Repeat every action mentioned in the paragraph before by yourself. Ask for help if anything isn’t clear or you didn’t manage to do it by yourself.
  4. Take a few photos of the motorbike, particularly take close-ups of all the cracks and scratches.
  5. Get on the bike and try the brakes gently while you are moving the bike forth and back with your legs.
  6. Start the engine and try to feel the throttle handle. Turn it gently and wait until the engine gains its frequency of rotation. Add a little more, feel the thrust.

Motorbike in Thailand, worth it or not?

Our trip to Thailand is drawing nearer and nearer. We must be prepared for the eventful day in the end of April. We are going to break out of the comfort zone. First of all we didn’t buy a tour from any travel agency. We did everything ourselves. We bought airplane tickets online, booked a hotel. Actually we booked a hotel for the first part of the trip only. Then we are going to move to another hotel for a change.  Don’t now what particular hotel it will be, we must decide as soon as possible. Honestly speaking, I hate to choose things like hotels. Since there is no certain ideal hotel that suits best for us. Every hotel has its advantages and disadvantages. They all good in different ways. More you hang around on the hotel websites, more you know, more your expectations become, more your disappointment will be when your high expectations will not meet the reality. So the right way is that you should feel the right choice by your heart. And don’t forget to use your head alongside your heart…

One more insane thing we are going to do is to rent a motorbike. I have been dreaming of it since I was in Thailand for the first time in 2014. Then we had a chance in Sri-Lanka in the fall of 2016 – yet we had few days thus we preferred to enjoy sun and ocean on the beach. I’m afraid for a number of reasons.

  1. I’ve got neither the A-class driver licence that allows me to ride a motorbike nor the international driver licence. Deal with paying fines…
  2. I’ve got little experience driving cars here as a whole.
  3. They drive on the left side of the road there and we drive on the right side in Russia. No big deal, really. I practiced left-side driving on Cyprus last February.
  4. The traffic is mad there. And almost everyone drives like a blondie. That fears me most. I ought to keep distance forward and at the sides, not to drive so fast. I ought to perform any manoeuvres carefully and extremely predictively.

So, for confidence I made up my make to take a couple of scooter lessons. I found a teacher on the Internet, arranged an appointment. We met under the bridge on the autodrome. It’s such a terrifying place. There are road all around crowded with roaring cars. Very noisy. The kingdom of concrete, metal and asphalt. Anyway my teacher was late so I struck up a conversation with another student while I was waiting. In the end he showed up riding his motorcycle. His name’s Dmitry. Cool man and awesome teacher. Indeed he is aware both driving rules and physics. We discussed lots of theory. It wasn’t just idle talk, I have learned tons of useful pieces of advice and hints. His manner of teaching is built around asking questions. That’s great as it makes you think compared with just listening and yawning. I had a theory exam by the way.

The lesson is supposed to last for exactly 1 hour. So I was afraid to miss a chance to practice on the real scooter. But my anxieties wore off. The lesson’s duration added up to 2 hours. I say you what. It’s not that easy to manage with a scooter. It has nothing to do with a bicycle even with an electrical bicycle. The scooter is much heavier. You sit on it in the absolutely different posture. I have learnt how to control the throttle stick and the brakes. During my first ride I felt unsteady. The scooter was wagging as I was trying to keep the balance.

Finally I realised that I had crucially needed those lessons. I don’t know that I would have done there without that experience and knowledge. Obviously I’ll take 2-3 more lessons as soon as I get back to Moscow.

I have firmly decided that we will rent a motorbike in Thailand as I don’t want that all will pass in vain.

That’s all for now. Good luck!