Thonny python как пользоваться

suit 690048 1920 Советы на день

Как установить и использовать Thonny Python IDE в Linux

Если вы новичок в программировании или кто-то переходит с другого языка, я предлагаю использовать thonny. Интерфейс чистый и не отвлекает. Новички могут сосредоточиться на языке, а не на настройке среды.

Некоторые из ключевых особенностей Thonny включают:

В этой статье вы узнаете, как установить и использовать Thonny Python IDE в среде Linux, а также познакомитесь с функциями thonny.

Настройка Thonny Python IDE в Linux

В демонстрационных целях я использую Ubuntu 20.04 и запускаю скрипт установщика с командой wget, как показано выше, для установки thonny. В конце установки вы узнаете, где установлен thonny. В моем случае он установлен в моем домашнем каталоге.

Thonny Installer

Чтобы запустить thonny, перейдите в установленный каталог и введите «./thonny» или абсолютный путь к thonny. Thonny попросит вас установить язык и начальные настройки.

Start Thonny IDE

Как показано в разделе установки, Thonny устанавливается в домашний каталог. Если вы посмотрите на папку thonny, в ней есть скрипт установки, необходимые библиотеки Python для работы thonny, двоичные файлы. Внутри каталога bin находятся python 3.7 и PIP 3, которые поставляются с двоичными файлами thonny и thonny.

Thonny Directory

Как использовать Thonny IDE в Linux

Когда вы запустите Thonny, вы получите удобный графический интерфейс. У вас будет область редактора, где вы можете кодировать и оболочку для интерактивного запуска скрипта или тестовых кодов.

Thonny IDE Editor

Дистрибутивы Linux по умолчанию поставляются с питоном. Более старая версия поставляется с Python2 *, а последние версии поставляются с Python3 *. Мы уже видели, что Python 3.7 установлен по умолчанию, а thonny устанавливает 3.7 в качестве интерпретатора по умолчанию.

Python Shell

Вы можете использовать интерпретатор по умолчанию (Python 3.7) или выбрать другие интерпретаторы, доступные в системе. Перейдите в «Строка меню → Инструменты → Параметры → Интерпретатор → Установить путь» или «Строка меню → Выполнить → Выбрать переводчика → Установить путь».

Set Thonny Python Interpreter

Я предлагаю придерживаться установки Python по умолчанию, если вы не знаете, как это исправить, если что-то сломается при переключении интерпретатора.

В Thonny есть светлая и темная темы. Вы можете изменить темы для редактора, а также тему пользовательского интерфейса. Чтобы изменить тему и шрифты, перейдите в «Строка меню → Инструменты → Параметры → Тема и шрифт».

Thonny IDE Theme

Есть 3 способа запустить созданный код. Во-первых, ваш код должен быть сохранен в файл для выполнения Тонни.

Первые два метода переключат каталог туда, где находится ваш код, и вызовут файл программы во встроенном терминале.

Run Programe in Thonny

Третий вариант позволяет запускать код во внешнем терминале.

Run Programe in External Terminal

Настоящая мощь thonny заключается в встроенных функциях, таких как проводник, обозреватель переменных, оболочка, помощник, заметки, куча, структура, стек. Чтобы включить или выключить эти функции Перейдите в «Просмотр → Переключить функцию ВКЛ./ВЫКЛ.».

Thonny Build in Features

Известно, что все пакеты python размещены на PyPI. Обычно мы будем использовать PIP (диспетчер пакетов Python) для установки желаемых пакетов из PyPI. Но с Thonny доступен графический интерфейс для управления пакетами.

Перейдите в «Строка меню → Инструменты → Пакеты». В строке поиска вы можете ввести имя пакета и нажать поиск. Он выполнит поиск в индексе PyPI и отобразит список пакетов, соответствующих названию.

В моем случае я пытаюсь установить вызов пакета numpy.

Search Package in Thonny

Когда вы выберете пакет из списка, вы попадете на страницу установки. Вы можете установить последнюю версию или выбрать другие версии, как показано на изображении. Зависимости устанавливаются автоматически.

Select Package Version

Как только вы нажмете «Установить», он установит пакет.

Install Package in Thonny

Вы можете получить подробную информацию, такую u200bu200bкак версия пакета, расположение библиотеки после установки пакета. В случае, если вы хотите удалить пакет, это просто, нажмите кнопку «удалить» в нижней части пакета, как показано на изображении.

Package Details

Thonny поставляется со встроенным отладчиком. Нажмите Ctrl + F5, чтобы запустить программу шаг за шагом, точки останова не требуются. Нажмите F7 для маленького шага и F6 для большего шага. Вы также можете получить доступ к этим параметрам из «Строка меню → Выполнить → Параметры отладки».

Thonny Debugger

Все конфигурации хранятся в файле «configuration.ini». Любые изменения, которые вы вносите в свой thonny-сеанс, записываются в этот файл. Вы также можете вручную отредактировать этот файл, чтобы установить различные параметры.

Чтобы открыть файл, перейдите в «Строка меню → Инструменты → Открыть папку данных Thonny».

Thonny Configuration File

Как удалить Thonny IDE в Linux

Если вы хотите удалить thonny, в каталоге установки thonny есть сценарий удаления.

Это все для этой статьи. В Тонни есть что исследовать, помимо того, что мы обсуждали здесь. Thonny отлично подходит для новичков, но текстовый редактор всегда остается личным выбором программистов. Установите Thonny play with it, поделитесь с нами своими отзывами.

Источник

How to Install and Use Thonny Python IDE on Linux

Thonny is an Integrated Development Environment (IDE) for Python beginners. It is created with Python and released under MIT License. It is cross-platform and can run in Linux, macOS, Windows.

Why Thonny IDE

If you are new to programming or someone switching from a different language I suggest using thonny. The interface is clean and distraction-free. Newbies can concentrate on language instead of focusing on setting up the environment.

Some of the key features of thonny include

In this article, you will learn how to install and use Thonny Python IDE in a Linux environment and exploring the features of thonny.

Setting Up Thonny Python IDE on Linux

The latest version of Thonny is 3.3.0 and there are three ways you can install thonny in Linux.

Install Thonny IDE Using Pip

Install Thonny IDE Using Installer Script

Install Thonny IDE Using Package Manager

For demonstration purposes, I am using Ubuntu 20.04 and running the installer script with wget command as shown above to install thonny. At the end of the installation, you will come to know where is thonny installed. In my case, it is installed in my home directory.

To launch thonny, go to the installed directory and type “./thonny” or absolute path to thonny. Thonny will ask you to set up Language and Initial settings.

As shown in the installation section, Thonny is installed in the home directory. If you look at the thonny folder it has install script, necessary python libraries for thonny to work, binaries. Inside the bin directory, there is python 3.7 and PIP 3 that comes with thonny and thonny launch binary.

How to Use Thonny IDE in Linux

When you launch Thonny you will get a distraction-free GUI interface. You will have an editor area where you can code and shell to run the script or test codes interactively.

Linux distributions by default ships with python. Older version ships with Python2* and the latest versions ship with Python3*. We have already seen Python 3.7 is installed by default and thonny sets 3.7 as the default interpreter.

Thonny Python Shell

You can stick with the default interpreter (Python 3.7) or choose different interpreters available on the system. Go to “Menu BarToolsOptionsInterpreterSet the path” or “Menu BarRun → Select InterpreterSet the path”.

Set Thonny Python Interpreter

I suggest sticking with the default python installation unless you know how to fix it if something breaks when switching the interpreter.

Thonny comes with Light and Dark themes. You can change themes for Editor as well as UI theme. To change Theme and Fonts Go to “Menu BarToolsOptionsTheme & Font”.

There are 3 ways you can run the code you created. First, your code should be saved to a file for Thonny to execute.

The first two methods will switch the directory to wherever your code is and invoke the program file in the Built-in terminal.

Run Programe in Thonny Terminal

The third option allows you to run your code in an external terminal.

Run Programe in External Terminal

The real power of thonny comes with built-in features like File Explorer, Variable Explorer, Shell, Assistant, Notes, Heap, Outline, Stack. To Toggle on-off these features Go to “View → toggle Feature ON/OFF”.

Thonny Build-in Features

Thonny Package Manager

It is known that all the python packages are hosted at PyPI. We will normally use PIP (Python Package Manager) to install desired packages from PyPI. But with Thonny, a GUI interface is available to manage packages.

Go to “Menu BarToolsPackages”. In the search bar, you can type a package name and press search. It will search the PyPI index and displays the list of package matching the name.

In my case, I am trying to install a package call numpy.

Search Package in Thonny

When you select the package from the list, It will take you to the installation page. You can install the latest version or choose different versions as shown in the image. Dependencies are automatically installed.

Select Package Version

Once you press Install, it will install the package.

Install Package in Thonny

You can get the details like package version, library location once the package is installed. In case if you wish to uninstall the package, it is simple, go ahead and click the “uninstall” button at the bottom of the package as shown in the image.

Thonny Debugging

Thonny comes with a built-in debugger. Press Ctrl+F5 to run your program step-by-step, no breakpoints needed. Press F7 for a small step and F6 for a bigger step. You can also access these option from “Menu BarRunDebugging options”.

Thonny Configuration

All the configurations are stored in the “configuration.ini” file. Any changes you make with your thonny session is written to this file. You can also manually edit this file to set different parameters.

To open the file go to “Menu BarToolsOpen Thonny data folder”.

Thonny Configuration File

How to Uninstall Thonny IDE in Linux

If you wish to uninstall thonny, there is an uninstall script available under the thonny installation directory.

That’s it for this article. There is a lot more to explore in Thonny than what we discussed here. Thonny is great for beginners but it is always a personal choice of programmers to choose which IDE or Text editor to work with. Install Thonny play with it, share your feedback with us.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

coffee

We are thankful for your never ending support.

Источник

Установка и использование модулей (библиотек) Python

Общие сведения:

В этой статье мы рассмотрим как работать и устанавливать модули для интерпретатора Python на Raspberry Pi в графической среде Raspbian.

Внимание! Для корректной работы модулей FLASH-I2C на Raspberry Pi под управлением Raspberry OS «Buster» необходимо выключить динамическое тактирование ядра (опция core_freq_min должна быть равна core_freq в /boot/config.txt ) Ссылка на подробное описание.

Нам понадобится:

Если из этого всего у вас есть только сама Raspberry, блок питания, SD карта и ПК с кард ридером — не переживайте, Raspberry можно настроить для подключения и удалённой работы по локальной сети при помощи этой статьи.

Предварительная настройка:

Для начала воспользуемся этой инструкцией для копирования образа диска системы на нашу microSD карту.

Если нужно работать с Rapberry по удалённому соединению (в случае отсутствия клавиатуры, мыши и монитора), можно воспользоваться этой статьёй.

Установка в графической среде:

Этот раздел объясняет процесс установки модулей Python в графической среде в редакторе Thonny Python IDE.

Курсором мыши наводим на пиктограмму малины в правом верхнем углу:

dd3c3b062fbd8833a37fb660e7979aee

b0a11f0d7ab813b988f8c97874a8b02b

Откроется окно Thonny Python IDE. Если под шапкой окна нет строки меню, нажимаем Switch to regular mode в правом верхнем углу, перезапускаем программу для применения изменений.

 fb8e5e52c32c36c063225c76d7b86557

fe049f7ca5e83d8d2fcc4c493fadac4e

Откроется окно установки пакетов:

e7fb059eef18cbf6cfb126a321b3a7ef

В строке поиска вводим название необходимого нам модуля, для примера возьмём наш модуль управления I2C реле pyiArduinoI2Crelay:

b652077fb6ebd628f972f4dae5567d47

После ввода нажимаем кнопку Search, справа от списка установленных модулей появится результат поиска. Нажимаем кнопку Install в нижней части окна:

40b8eb7860dde74a8f6431f2ffcf5597

Начнётся процесс установки, нужно немного подождать (это займет не больше минуты):

e600fd7d4b2904796c5d975f205a12ee

После установки модуль появится в списке установленных:

c963bd25dd47224db0c052cd0b40d01e

Теперь можно использовать его методы, но работать он будет только в Thonny Python IDE.

Попробуем написать и запустить следующий скрипт:

9f5c352e7f4687590d0174aeb93365d3

5b856c9898eb186ed31c9dc9655e68ac

Установка в эмуляторе терминала:

Для использования модуля в качестве системного его нужно установить от имени супер-пользователя из командной строки. Этот раздел разъясняет этот процесс.

Нажимаем курсором мыши на пиктограмму виртуального терминала LXTerminal в верхнем меню:

d2c043eb2806727f4e44a29a4d7aee37

Откроется окно виртуального терминала. Вводим с клавиатуры sudo pip3 install pyiArduinoI2Crelay и нажимаем клавишу enter, начнётся процесс установки:

0bc53b2f86c8716bf5a6d5b7085b4f09

Теперь можно пользоваться методами модуля.

Вводим с клавиатуры python3 и нажимаем enter, откроется строка ввода интерпретатора Python обозначаемая тремя правыми треугольными скобками «>>>»:

b492f6742ea7af7af995a3bd172ec489

72f730ca21b4f5ba557bcf492cd6c3c5

Для выхода из интерпретатора наберем на клавиатуре exit() и нажмем enter

Источник

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

Thonny.jpg.500x0 q85 crop smart

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

Характеристики:

Python часто предлагается в качестве отличного языка программирования для начинающих, так как он является относительно интуитивным и в то же время достаточно универсальным. С помощью специализированного инструмента обучения можно начать создавать свои собственные программы в кратчайшие сроки.

Thonny является одним из таких приложений, Python IDE, разработанная для новичков. Среда python очень проста в развертывании, и ее могут использовать новички, а также преподаватели, которые хотят объяснить различные концепции своим студентам.

Программа включает Python в установочный пакет, поэтому нет необходимости загружать и настраивать любые другие компоненты. Конечно, также можно использовать отдельную установку Python, если необходимо.

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

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

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

Режим отладки позволяет выполнять программы Шаг за шагом с помощью удобных горячих клавиш, и также можно посмотреть, как оцениваются выражения. Вызовы функций отображаются в новом окне с отдельной таблицей локальных переменных и указателем кода.

Кроме того, приложение может выделить переменные, чтобы помочь пользователям избежать опечаток, и переключиться на более реалистичную модель представления переменных.

Источник

Thonny on a Raspberry Pi: using the new Python IDE in Raspbian

By Russell Barnes. Posted over 4 years ago.

thonny

Use the new Thonny IDE in Raspbian on a Raspberry Pi to understand what’s going on in your code

MagPi113 COVER WEB

The MagPi issue 113 out now

Discover everything you need to know about Raspberry Pi for the year 2022 with our New User Guide. Our January issue is packed with information for newcomers about Raspberry Pi OS (bullseye) along with new information for seasoned hands with Raspberry Pi OS (Legacy). We have all your questions answered alongside in-depth guidance from the engineering team.

apple app store 01f99066cee4ad3e87a3b4aff63e571ec96f86907e2945e50bc2705ea4f12333

google play store a0bc1b3038a34936be22269b5d3044697551826287decc9b5b9665928006823a

Thonny is a new IDE (integrated development environment) bundled with the latest version of the Raspbian with PIXEL operating system. Using Thonny, it’s now much easier to learn to code. Thonny comes with Python 3.6 built in, so you don’t need to install anything.

Just open up the program, which you’ll find under Menu > Programming. It offers a lot of advanced features not currently available in the Python 3 (IDLE) program, which is still included with Raspbian.

When you start Thonny, you’ll see a new script editor and a shell. As with Python 2/3 IDLE, you enter a program in the script editor and run it in the shell. You can then use the shell to interact directly with the program; accessing variables, objects, and other program features.

Thonny has a range of additional features that are perfect for learning programming. One of the best features is a powerful, but easy-to-use, debug mode. Instead of running your program, it steps through the code line by line. You can see the variables and objects being created, and values being passed into functions or assessed by comparators.

You often find debuggers in powerful IDEs, but they tend to require you to manually set breakpoints (places where the program freezes so you can examine the code). The approach in Thonny is much more straightforward. It also has a range of panels that enable you to inspect various items, such as variables, objects, and the heap (the memory space where items are stored).

There’s some pretty good stuff in Thonny for young coders. The ability to step through your programs makes it much easier to understand what happens when you hit Run.

>STEP-01: How to use Thonny

step1 thonny

Click the Raspberry Pi Menu icon in the top left of the screen and choose Programming > Thonny Python IDE. We’ve used File > Increase Font Size so you can see the text more clearly. Enter this line of code in the script editor:

Now choose File > Save and name the program hello.py. Click Run current script (or press F5) to see the output in the shell. As with IDLE, you can also enter commands directly in the shell, such as:

>STEP-02: Coding in Thonny

step2 thonny

Let’s see how you can walk through a file and see a variable change. Create a new script (File > New) and enter the code in countdown.py.

>STEP-03 Debug Python code in Thonny

step3 thonny

Choose View > Variables and a new window appears displaying n and its current value (which is zero). Now let’s run through it one step at a time. Click ‘Debug current script’. The first line will be highlighted. Click Step Into and the value will be highlighted. Click it again, and both ‘n’ and ‘10’ are placed in the Variables window.

>STEP-04: Step through Python code in Thonny

step4 thonny

Keep clicking Step Into and you will see the value of variable n (which is 10) added to the comparator and evaluated to True. Then the while loop will activate, the value of n will be displayed to the console, and n will decrease by 1. Click Step Out to run through the while loop and back to the main code.

>STEP-05: Understand Recursion in Thonny

step5 thonny

Thonny’s debug mode makes it easier to understand concepts such as recursion. Our countdown_recursion.py program runs a countdown recursively (a function which calls itself from inside itself).

When the function calls itself, a new window appears with the function. Keep stepping through to see the values updated.

>STEP-06: Look at Heap and objects in Thonny

step6 thonny.py

For a more detailed view, enter View > Heap and View > Objects. Now, as you work with object-oriented code, you can select objects in the Heap or Variables window and use the Object Inspector to check their type and attributes. The animals.py code creates animal objects with creature and name instance variables.

Russell Barnes

Russell runs Raspberry Pi Press, which includes The MagPi, Wireframe, and HackSpace magazine, and book projects. He’s a massive sci-fi bore.

Источник

Оцените статью
Добавить комментарий

Adblock
detector