---
June 16, 2020, 4:42 p.m.

Python 10 line toast notifications

Introduction

We often use print to monitor the state of a script, or when we're debugging. Instead of constantly looking at the terminal window and waiting for some kind of output, we can use toast notifications as a way to view the output while doing something else.

This is not at all difficult to do - we will use the built-in commands of our operating system to display notifications, simply by running them through Python. A few lines of code, and no third-party modules.


Mac OS

The following command runs AppleScript (Apple's built-in scripting language) for notifications.

osascript -e 'display notification "Your message goes here" with title "Title"'

If you run this command you will see the following output:

Result of script execution

More about the script itself:

Command description

So, if you are using Mac OS, then you can run the following Python code:

  1. import os
  2. title = "Готово"
  3. message = "Файл скачан"
  4. command = f'''
  5. osascript -e 'display notification "{message}" with title "{title}"'
  6. '''
  7. os.system(command)

By running this script, you will see a similar result as above.

Linux

Linux offers an even simpler option:

notify-send "Your message" "Title"

Similar to how we displayed a notification on Mac OS via os.system, you can do the same on a Linux system.

Windows

On Windows there is no such command that would trigger notifications like on Linux and Mac OS, but it can still be done using the win10toast library, first you need to install it: pip install win10toast and now an example of its use:

  1. import win10toast
  2.  
  3. toaster = win10toast.ToastNotifier()
  4. toaster.show_toast("Заголовок", "Описание уведомления")

The show_toast method also accepts other arguments, but you can read more about them directly - just by calling help passing it the object of the function you want to know more about.

Making the script cross-platform

To find out what system is on your computer, use the system() command from the built-in platform library. For Mac OS, this command returns the string "Darwin", for Linux "Linux", for Windows - "Windows", now, knowing all this, we can put all the code in the push function. Here's what happens:

  1. import platform, os
  2.  
  3. def push(title, message):
  4. plt = platform.system()
  5. if plt == "Darwin":
  6. command = '''
  7. osascript -e 'display notification "{message}" with title "{title}"'
  8. '''
  9. elif plt == "Linux":
  10. command = f'''
  11. notify-send "{title}" "{message}"
  12. '''
  13. elif plt == "Windows":
  14. win10toast.ToastNotifier().show_toast(title, message)
  15. return
  16. else:
  17. return
  18. os.system(command)

Conclusion

The article showed how to display toast notifications in Python, but it certainly wasn't the only way. There are a sufficient number of libraries that fulfill such goals.

By article asked0question(s)

2

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html