Как настроить pycharm для python
Перейти к содержимому

Как настроить pycharm для python

  • автор:

Getting started with PyCharm

In the previous two posts of this absolute beginner series, we installed Anaconda Navigator and learned about virtual environments. Having completed the basic setup, it’s now time to choose an IDE and get to coding.

I should mention from the start that choosing and IDE is not crucial when starting learning. Just go with anything that is comfortable for you… Any recommendations in this post are my preferences which might not match yours. That is absolutely fine, all is subjective 🙂

PyCharm Installation and Setup

PyCharm is developed by JetBrains which produces IDE applications for many popular languages (Javascript, C/C++, PHP, Ruby etc.). I’ve worked with PHPStorm for several years before starting with Python, so my transition to PyCharm was quite smooth.

PyCharm is available for download on Windows, Mac and Linux. The Professional Edition trial is 30 days, but, unlike other of their IDEs, JetBrains offers a perpetually free Community Edition.

Download and installation is a straightforward process. When launching PyCharm for the first time, you’ll have to go through a couple of settings. Choose a dark or light theme (I chose the dark side if anyone wonders �� ) and skip installation of other plugins for now. As a side note, you might notice that one of the plugins is for supporting the R language which was mentioned as an alternative to Python.

After setup is complete, you’ll see the welcome screen. It’s time to create our first project in PyCharm.

Creating a Project

On the Welcome screen, simply click Create a Project.

I’ve named the project learning_project. It will have its own folder on the disk. I’ve left the default path, but you can place the project wherever you wish.

Expanding Project Interpreter: New Virtualenv environment we can see more details about the project.

Most important, PyCharm will create a new virtual environment for this project. This is done for all new projects, without any additional settings having to be made. Quite handy…

Then we see the base interpreter is the python we installed with Anaconda. So PyCharm recognizes any existing Python installations.

The other 2 checkbox options are more advanced, so there’s no need to worry about them for now.

Creating a Python file and running it

On the left side of the UI we see the Project. Right click on its name and create a new Python file.

In the Python file add the same code from the numpy test in the previous post:

To run the file, press CTRL+SHIFT+F10 (or just SHIFT+F10, depending on version). You’ll see the following error: No module named ‘numpy’

Do you have any idea what the problem is?

Well, we haven’t installed numpy inside this project’s virtual environment.

Installing a Package in PyCharm

Packages in PyCharm can be installed using pip, the package installation manager for Python.

In the lowest bar of the UI, click on terminal and type

pip will then download and install the package inside the virtual environment. Any dependencies will automatically be collected and installed as well.

When the installation is successfully complete, you should see the following:

Running the file again will prove successful this time, with the expected value [1, 2, 3] being displayed on the screen.

Having a virtual environment automatically created for every project is just one of PyCharm’s features. The Getting started guide on the official site provides more thorough introduction.

Alternatives to PyCharm

There are of course many alternatives to PyCharm, which proves Python is a very popular language. Two are available inside Anaconda Navigator: Spyder and Visual Studio Code.

Spyder

Spyder is a Python IDE aimed specifically at Data Scientists. You can check out a great overview video here.

Visual Studio Code

A lightweight free code editor from Microsoft, Visual Studio Code is available on all platforms. It’s not set up for Python out of the box, but it has official Python support via an extension. Check out the get started guide.

Atom

Like Visual Studio Code, Atom is a light editor, not specific to Python, but highly configurable and offering Python support via extensions.

If you want to read more, here is a great overview of IDEs and code editors for Python: https://realpython.com/python-ides-code-editors-guide/

Conclusion

You can check them all out before deciding which one to use. My advice is not to dwell too much on this now, any option is good enough to start learning about Python, Machine Learning or Data Science… and you can always switch IDEs when you are more experienced.

Next post will be an overview of Jupyter Notebooks, an indispensable tool for any Python user.

Your opinions, feedback or (constructive) criticism are welcomed in discussions below or at @mariussafta

Join our Facebook and Meetup groups and keep an eye out for discussions and future meetups.

Step 1. Create and run your first Python project

You have installed Python itself. If you’re using macOS or Linux, your computer already has Python installed. You can get Python from python.org.

To get started with PyCharm, let’s write a Python script.

Create a Python project

If you’re on the Welcome screen, click New Project . If you’ve already got any project open, choose File | New Project from the main menu.

Although you can create projects of various types in PyCharm, in this tutorial let’s create a simple Pure Python project. This template will create an empty project.

Choose the project location. Click button next to the Location field and specify the directory for your project.

Also, deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.

Python best practice is to create a virtualenv for each project. In most cases, PyCharm create a new virtual environment automatically and you don’t need to configure anything. Still, you can preview and modify the venv options. Expand the Python Interpreter: New Virtualenv Environment node and select a tool used to create a new virtual environment. Let’s choose Virtualenv tool, and specify the location of the environment and the base Python interpreter used for the new virtual environment.

If PyCharm detects no Python on your machine, it provides the following options:

Specify a path to the Python executable (in case of non-standard installation)

Download and install the latest Python versions from python.org

Install Python using the Command-Line Developer Tools (macOS only).

Downloading Python when creating a new project

Downloading Python when creating a new project

Now click the Create button at the bottom of the New Project dialog.

If you’ve already got a project open, after clicking Create PyCharm will ask you whether to open a new project in the current window or in a new one. Choose Open in current window — this will close the current project, but you’ll be able to reopen it later. See the page Open, reopen, and close projects for details.

Create a Python file

In the Project tool window, select the project root (typically, it is the root node in the project tree), right-click it, and select File | New . .

Select the option Python File from the context menu, and then type the new filename.

Creating a new Python file

PyCharm creates a new Python file and opens it for editing.

Edit Python code

Let’s start editing the Python file you’ve just created.

Start with declaring a class. Immediately as you start typing, PyCharm suggests how to complete your line:

Create class completion

Choose the keyword class and type the class name, Car .

PyCharm informs you about the missing colon, then expected indentation:

Create class analysis

Note that PyCharm analyses your code on-the-fly, the results are immediately shown in the inspection indicator in the upper-right corner of the editor. This inspection indication works like a traffic light: when it is green, everything is OK, and you can go on with your code; a yellow light means some minor problems that however will not affect compilation; but when the light is red, it means that you have some serious errors. Click it to preview the details in the Problems tool window.

Let’s continue creating the function __init__ : when you just type the opening brace, PyCharm creates the entire code construct (mandatory parameter self , closing brace and colon), and provides proper indentation.

If you notice any inspection warnings as you’re editing your code, click the bulb symbol to preview the list of possible fixes and recommended actions:

Let’s copy and paste the entire code sample. Hover the mouse cursor over the upper-right corner of the code block below, click the copy icon, and then paste the code into the PyCharm editor replacing the content of the Car.py file:

This application is intended for Python 3

At this point, you’re ready to run your first Python application in PyCharm.

Run your application

Use either of the following ways to run your code:

Right-click the editor and select Run ‘Car’ from the context menu .

Since this Python script contains a main function, you can click an icon in the gutter. If you hover your mouse pointer over it, the available commands show up:

Running a script

If you click this icon, you’ll see the popup menu of the available commands. Choose Run ‘Car’ :

PyCharm executes your code in the Run tool window.

Run Tool window

Here you can enter the expected values and preview the script output.

Note that PyCharm has created a temporary run/debug configuration for the Car file.

Temporary run/debug configuration

The run/debug configuration defines the way PyCharm executes your code. You can save it to make it a permanent configuration or modify its parameters. See Run/debug configurations for more details about running Python code.

Summary

Congratulations on completing your first script in PyCharm! Let’s repeat what you’ve done with the help of PyCharm:

Get started

PyCharm is a dedicated Python Integrated Development Environment (IDE) providing a wide range of essential tools for Python developers, tightly integrated to create a convenient environment for productive Python, web, and data science development.

Choose the best PyCharm for you

PyCharm is available in three editions:

Community (free and open-sourced): for smart and intelligent Python development, including code assistance, refactorings, visual debugging, and version control integration.

Professional (paid) : for professional Python, web, and data science development, including code assistance, refactorings, visual debugging, version control integration, remote configurations, deployment, support for popular web frameworks, such as Django and Flask, database support, scientific tools (including Jupyter notebook support), big data tools.

Supported languages

To start developing in Python with PyCharm you need to download and install Python from python.org depending on your platform.

PyCharm supports the following versions of Python:

Python 2: version 2.7

Python 3: from the version 3.6 up to the version 3.12

Besides, in the Professional edition, one can develop Django , Flask, and Pyramid applications. Also, it fully supports HTML (including HTML5), CSS, JavaScript, and XML: these languages are bundled in the IDE via plugins and are switched on for you by default. Support for the other languages and frameworks can also be added via plugins (go to Settings | Plugins or PyCharm | Settings | Plugins for macOS users, to find out more or set them up during the first IDE launch).

Supported platforms

PyCharm is a cross-platform IDE that works on Windows, macOS, and Linux. Check the system requirements:

4 GB of free RAM

8 GB of total system RAM

Multi-core CPU. PyCharm supports multithreading for different operations and processes making it faster the more CPU cores it can use.

2.5 GB and another 1 GB for caches

SSD drive with at least 5 GB of free space

Officially released 64-bit versions of the following:

Microsoft Windows 8 or later

macOS 10.14 or later

Any Linux distribution that supports Gnome, KDE , or Unity DE. PyCharm is not available for some Linux distributions, such as RHEL6 or CentOS6, that do not include GLIBC 2.14 or later.

Pre-release versions are not supported.

Latest 64-bit version of Windows, macOS, or Linux (for example, Debian, Ubuntu, or RHEL)

You can install PyCharm using Toolbox or standalone installations. If you need assistance installing PyCharm, see the installation instructions: Install PyCharm

Start with a project in PyCharm

Everything you do in PyCharm, you do within the context of a project. It serves as a basis for coding assistance, bulk refactoring, coding style consistency, and so on. You have three options to start working on a project inside the IDE:

Open an existing project

Begin by opening one of your existing projects stored on your computer. You can select one in the list of the recent projects on the Welcome screen or click Open :

Welcome screen

Otherwise, you can create a project for your existing source files. Select the command Open on the File menu, and specify the directory where the sources exist. PyCharm will then create a project from your sources for you. Refer to the section Create a project from existing sources for details.

Check out an existing project from Version Control

You can also download sources from a VCS storage or repository. Choose Git (GitHub), Mercurial, Subversion, Perforce (supported in Professional edition only), and then enter your credentials to access the storage.

Then, enter a path to the sources and clone the repository to the local host:

Clone a repository

Refer to the section Version control for details.

Create a new project

To create a project, do one of the following:

From the main menu, choose File | New Project

On the Welcome screen, click New Project

In PyCharm Community, you can create only Python projects, whereas, with PyCharm Professional, you have a variety of options to create a web framework project.

Creating a new project

Creating a PyCharm helps implement new project

When creating a new project, you need to specify a Python interpreter to execute Python code in your project. You need at least one Python installation to be available on your machine.

For a new project, PyCharm creates an isolated virtual environment : venv, pipenv, poetry, or Conda. As you work, you can change it or create new interpreters. You can also quickly preview packages installed for your interpreters and add new packages in the Python Package tool window.

Python Package tool window

Look around

When you launch PyCharm for the very first time, or when there are no open projects, you see the Welcome screen. It gives you the main entry points into the IDE: creating or opening a project, checking out a project from version control, viewing documentation, and configuring the IDE.

When a project is opened, you see the main window divided into several logical areas. Let’s take a moment to see the key UI elements here:

Project tool window on the left side displays your project files.

Editor on the right side, where you actually write your code. It has tabs for easy navigation between open files.

Navigation bar above the editor additionally allows you to quickly run and debug your application as well as do the basic VCS actions.

Gutter , the vertical stripe next to the editor, shows the breakpoints you have, and provides a convenient way to navigate through the code hierarchy like going to definition/declaration. It also shows line numbers and per-line VCS history.

Scrollbar , on the right side of the editor. PyCharm constantly monitors the quality of your code and always shows the results of its code inspections in the gutter: errors, warnings, and so on. The indicator in the top right-hand corner shows the overall status of code inspections for the entire file.

Tool windows are specialized windows attached to the bottom and sides of the workspace and provide access to typical tasks such as project management, source code search and navigation, integration with version control systems, and so on.

The status bar indicates the status of your project and the entire IDE, and shows various warnings and information messages like file encoding, line separator, inspection profile, and so on. It also provides quick access to the Python interpreter settings.

Also, in the bottom-left corner of the PyCharm window, in the Status bar, you see the button or. This button toggles the showing of the tool window bars. If you hover your mouse pointer over this button, the list of the currently available tool windows show up.

See the pages User interface and Tool windows to learn more about showing or hiding tool windows.

Code with smart assistance

When you have created a new project or opened an existing one, it is time to start coding.

Create a Python file

In the Project tool window, select the project root (typically, it is the root node in the project tree), right-click it, and select File | New . .

Select the option Python File from the context menu, and then type the new filename.

Creating a new Python file

PyCharm creates a new Python file and opens it for editing.

PyCharm takes care of the routine so that you can focus on the important. Use the following coding capabilities to create error-free applications without wasting precious time.

Code completion

Code completion is a great time-saver, regardless of the type of file you’re working with.

Basic completion works as you type and completes any name instantly.

Smart type-matching completion analyzes the context you’re currently working in and offers more accurate suggestions based on that analysis.

Smart code completion

Intention actions

PyCharm keeps an eye on what you are currently doing and makes smart suggestions, called intention actions, to save more of your time. Indicated with a lightbulb, intention actions let you apply automatic changes to code that is correct (in contrast to code inspections that provide quick-fixes for code that may be incorrect ). Did you forget to add some parameters and field initializers to the constructor? Not a problem with PyCharm. Click the lightbulb (or press Alt+Enter ) and select one of the suggested options:

Intention Action

The full list of available intention actions can be found in File | Settings | Editor | Intentions or PyCharm | Settings | Editor | Intentions for macOS users.

Keep your code neat

PyCharm monitors your code and tries to keep it accurate and clean. It detects potential errors and problems and suggests quick-fixes for them.

Every time the IDE finds unused code, an endless loop, and many other things that likely require your attention, you’ll see a lightbulb. Click it, or press Alt+Enter , to apply a fix.

The complete list of available inspections can be found under Settings | Editor | Inspections (or PyCharm | Settings | Editor | Inspections for macOS users). Disable some of them, or enable others, plus adjust the severity of each inspection. You decide whether it should be considered an error or just a warning.

Generate some code

Writing code can be a lot easier and quicker when you use the code generation options available in PyCharm. The Code | Generate menu Alt+Insert will help you with creating symbols from usage, as well as suggest overriding or implementing some functions:

Generate code

Use live templates (choose Code | Insert Live Template or press Ctrl+J ) to produce the entire code constructs. You can explore the available ready-to-use live templates In the Settings dialog ( Ctrl+Alt+S ) (Settings | Editor | Live templates or PyCharm | Settings | Editor | Live Templates if you are a macOS user).

If you see that you are lacking something especially important for your development, extend this set of templates with your own. Also, consider quickly surrounding your code with complete constructs (choose Code | Surround With or press Ctrl+Alt+T . For example, with an if statement:

Surround code

Find your way through

When your project is big, or when you have to work with someone else’s code, it’s vital to be able to quickly find what you are looking for and dig into the code. This is why PyCharm comes with a set of navigation and search features that help you find your way through any code no matter how tangled it is.

Basic search

With these search facilities, you can find and replace any fragment of code both in the currently opened file Ctrl+F , or in an entire project Ctrl+Shift+F .

Search for usages

To find where a particular symbol is used, PyCharm suggests full-scale search via Find Usages Alt+F7 :

Find usages

Project navigation

You can tell a lot just looking at your File Structure, with its imports or call hierarchies:

File structure

Also, you can navigate to:

The icons in the left-hand gutter can also help you with navigation:

Navigating by using the left-hand gutter

Navigate through the timeline

Remembering all your activity in the project, PyCharm can easily navigate you to the Recent Files Ctrl+E or Recently Changed Files Alt+Shift+C .

To go through the history of changes, try using Back/Forward navigation ( Ctrl+Alt+Left / Ctrl+Alt+Right ) and/or go to last edit location Ctrl+Shift+Backspace .

Search Everywhere

If you have a general idea of what you’re looking for, you can always locate the corresponding element using one of the existing navigation features. But what if you want to look for something in every nook and cranny? The answer is to use Search Everywhere!

To try it, click the magnifying glass button in the upper right-hand corner of the window, or invoke it with Double Shift (press Shift twice).

search everything window

Run, debug and test

Now when you’ve played with the code and discovered what you can do with it, it’s time to run, debug and test your app.

The easiest way to run an application is to right-click in the editor, and then choose Run <name> from the context menu:

Running code

If your Python script contains the __main__ clause, then you can click the button in the gutter, and then choose the desired command.

You can see the your script execution in the Run tool window.

Run tool window

When you perform run, debug, or test operations with PyCharm, you always start a process based on one of the existing run/debug configurations , using its parameters.

When you run your application for the very first time, PyCharm automatically creates the temporary Run/Debug configuration. You can modify it to specify or alter the default parameters and save it as a permanent Run/Debug configuration.

See how to tune run/debug configurations in Run/debug configurations.

Debug

Does your application stumble on a runtime error? To find out what’s causing it, you will have to do some debugging. PyCharm supports the debugger on all platforms.

Debugging starts with placing breakpoints at which program execution will be suspended, so you can explore program data. Just click the gutter of the line where you want the breakpoint to appear.

To start debugging your application, press Shift+F9 . Then go through the program execution step by step (see the available options in the Run menu or the Debug tool window), evaluate any arbitrary expression, add watches, and manually set values for the variables.

Debug tool window

Refer to the section Debugging for details.

It is a good idea to test your applications, and PyCharm helps doing it as simple as possible.

With PyCharm, you can:

Run and debug tests right from the IDE, using the testing run/debug configurations.

And, finally, the most important thing — you can explore test results in the test runner tab of the Run tool window:

To learn about the numbers, read the Test Runner tab section.

PyCharm supports all the major Python testing frameworks:

For each of these frameworks, PyCharm provides its own run/debug configuration.

Refer to tutorial Step 3. Test your first Python application and to the Run tests section for details.

With PyCharm Professional you can run, debug, and test your Python code remotely. You can deploy your local applications to some remote server. To learn about deployment servers, refer to the section Configuring Synchronization with a Web Server. PyCharm Professional also helps compare local and remote folders, and synchronize the local copy with that deployed on the server.

Keep your source code under Version Control

If you are keeping your source code under version control, you will be glad to know that PyCharm integrates with many popular version control systems: Git (or GitHub), Mercurial, Perforce (supported in Professional edition only), Subversion. To specify credentials and any settings specific to a particular VCS, go to Settings | Version Control (or PyCharm | Settings | Version Control if you are a macOS user).

The VCS menu gives you a clue about what commands are available. For example, you can see the changes you’ve made, commit them, create changelists and much more from the Local Changes view: VCS | Show Changes (or just press Alt+9 ). Also, find some VCS basic commands in the Navigation bar above the editor:

Version Control System

Refer to the section Version control for details.

Local history

In addition to traditional version control, you can use the local history. With Local History, PyCharm automatically tracks changes you make to the source code, the results of refactoring, and so on

Local history is always enabled. To view it for a file or a folder, bring up Local History by selecting VCS | Local History | Show History . Here you can review the changes, revert them, or create a patch.

Process data

PyCharm has an interactive Python console to perform smart operations over data with on-the-fly syntax check with inspections, braces and quotes matching, and of course, code completion. You can also benefit from the built-in support for Anaconda.

Jupyter notebook support

With PyCharm Professional , you can analyze and visualize various scientific and statistical data. Jupyter Notebook integration enables editing, executing, and debugging notebook source code and examining execution outputs, including stream data, images, and other media.

R plugin

With the R plugin installed in PyCharm, you can perform various statistical computing using R language and use coding assistance, visual debugging, smart running and preview tools, and other popular IDE features.

As you might have noticed already, creating projects of the various types (Django, for example) requires a data source. It is also quite possible that you inject SQL statements into your source code.

PyCharm Professional does not enable you to create databases, but provides facilities to manage and query them. Once you are granted access to a certain database, you can configure one or more data sources within PyCharm that reflect the structure of the database and store the database access credentials. Based on this information, PyCharm establishes a connection to the database and provides the ability to retrieve or change information contained therein.

Access to the databases is provided by the Database window ( View | Tool Windows | Database ). This tool window allows you to work with the databases. It lets you view and modify data structures in your databases, and perform other associated tasks.

DB tool window

Customize your environment

Feel free to tweak the IDE so it suits your needs perfectly and is as helpful and comfortable as it can be. Go to Settings to see the list of available customization options.

Appearance

The first thing to fine-tune is the general "look and feel." Go to File | Settings | Appearance and Behavior | Appearance ( PyCharm | Settings | Appearance and Behavior | Appearance for macOS users) to select the IDE theme: the light themes or Darcula if you prefer a darker setting.

Editor

The many pages available under File | Settings | Editor ( PyCharm | Settings | Editor for macOS users) help you adjust every aspect of the editor’s behavior. A lot of options are available here, from general settings (like Drag’n’Drop enabling, scrolling configuration, and so on.), to color configuration for each available language and use case, to tabs and code folding settings, to code completion behavior and even postfix templates.

Refer to the section Configuring PyCharm settings for details.

Code style

Code style can be defined for each language under File | Settings | Editor | Code Style ( PyCharm | Settings | Editor | Code Style for macOS users). You can also create and save your own coding style scheme.

Code style settings

Keymap

PyCharm uses the keyboard-centric approach, meaning that nearly all actions possible in the IDE are mapped to keyboard shortcuts.

The set of keyboard shortcuts you work with is one of your most intimate habits — your fingers "remember" certain combinations of keys, and changing this habit is easier said than done. PyCharm supplies you with a default keymap (choose Help | Keyboard Shortcuts PDF from the main menu) making your coding really productive and convenient. However, you can always change it going to File | Settings | Keymap ( PyCharm | Settings | Keymap for macOS users).

There are also some pre-defined keymaps (like Emacs, Visual Studio, Eclipse, NetBeans and so on), and you can also create your own keymap based on an existing one.

If you feel most productive with vi/Vim , an emulation mode will give you the best of both worlds. Enable the IdeaVim plugin in the IDE and select the vim keymap.

Refer to the section Configure keyboard shortcuts for details.

That’s it! Go ahead and develop with pleasure!

We hope this brief overview of essential PyCharm features will give you a quick start. There are many important features that make a developer’s life easier and more fun, and the source code neater and cleaner. Take these first few steps now, and then dig deeper when you feel the time is right:

Enjoy PyCharm! With any questions visit our Discussion Forum, twitter and blog, where you can find news, updates, and useful tips and tricks. Also, don’t hesitate to report any problems to our support team) or the PyCharm issue tracker.

Создание виртуальных окружений и установка библиотек для Python 3 в IDE PyCharm

Язык программирования Python считается достаточно простым. На нем легче и быстрее пишутся программы, по сравнению с компилируемыми языками программирования. Для Python существует множество библиотек, позволяющих решать практически любые задачи. Есть, конечно, и минусы и другие нюансы, но это отдельная тема.

Довольно часто я вижу, как мои знакомые и друзья начинают изучать Python и сталкиваются с проблемой установки и использования сторонних библиотек. Они могут несколько часов потратить на установку библиотеки, и даже, могут не справиться с этим и забить на неё. В то время как, в большинстве случаев, это можно было сделать за несколько минут.

Статья начинается с базовых вещей: с установки Python 3, инструментов разработки Pip и Virtualenv и среды разработки PyCharm в Windows и в Ubuntu. Для многих это не представляет трудностей и возможно, что уже всё установлено.

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

Установка Python и Pip

Pip является менеджером пакетов для Python. Именно с помощью него обычно устанавливаются модули/библиотеки для разработки в виде пакетов. В Windows Pip можно установить через стандартный установщик Python. В Ubuntu Pip ставится отдельно.

Установка Python и Pip в Windows

Для windows заходим на официальную страницу загрузки, где затем переходим на страницу загрузки определенной версии Python. У меня используется Python 3.6.8, из-за того, что LLVM 9 требует установленного Python 3.6.

Далее в таблице с файлами выбираем «Windows x86-64 executable installer» для 64-битной системы или «Windows x86 executable installer» для 32-битной. И запускаем скачанный установщик, например, для версии Python 3.8.1 он называется python-3.8.1-amd64.exe .

Во время установки ставим галочку возле Add Python 3.x to PATH и нажимаем Install Now:

Установка Python 3 в Windows 10

Установка Python и Pip в Ubuntu

В Ubuntu установить Python 3 можно через терминал. Запускаем его и вводим команду установки. Вторая команда выводит версию Python.

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

Основные команды Pip

Рассмотрим основные команды при работе с Pip в командой строке Windows и в терминале Ubuntu.

Команда Описание
pip help Справка по командам
pip search package_name Поиск пакета
pip show package_name Информация об пакете
pip install package_name Установка пакета(ов)
pip uninstall package_name Удаление пакета(ов)
pip list Список установленных пакетов
pip install -U Обновление пакета(ов)

Если виртуальные окружения не используются, то во время установки пакета(ов) полезно использовать дополнительно ключ —user , устанавливая пакет(ы) локально только для текущего пользователя.

Установка VirtualEnv и VirtualEnvWrapper

VirtualEnv используется для создания виртуальных окружений для Python программ. Это необходимо для избежания конфликтов, позволяя установить одну версию библиотеки для одной программы, и другу для второй. Всё удобство использования VirtualEnv постигается на практике.

Установка VirtualEnv и VirtualEnvWrapper в Windows

В командной строке выполняем команды:

Установка VirtualEnv и VirtualEnvWrapper в Ubuntu

Для Ubuntu команда установки будет следующей:

После которой в конец

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

Работа с виртуальным окружением VirtualEnv

Рассмотрим основные команды при работе с VirtualEnv в командой строке Windows и в терминале Ubuntu.

Команда Описание
mkvirtualenv env-name Создаем новое окружение
workon Смотрим список окружений
workon env-name Меняем окружение
deactivate Выходим из окружения
rmvirtualenv env-name Удаляем окружение

Находясь в одном из окружений, можно ставить пакеты через Pip, как обычно и нет необходимости добавлять ключ —user :

Для Windows можно указать в переменных среды WORKON_HOME для переопределения пути, где хранятся виртуальные окружения. По умолчанию, используется путь %USERPROFILE%\Envs .

Установка PyCharm

PyCharm — интегрированная среда разработки для языка программирования Python. Обладает всеми базовыми вещами необходимых для разработки. В нашем случае огромное значение имеет хорошее взаимодействие PyCharm с VirtualEnv и Pip, чем мы и будем пользоваться.

Установка PyCharm в Windows

Скачиваем установщик PyCharm Community для Windows с официального сайта JetBrains. Если умеете проверять контрольные суммы у скаченных файлов, то не забываем это сделать.

В самой установке ничего особенного нету. По сути только нажимаем на кнопки next, и в завершение на кнопку Install. Единственно, можно убрать версию из имени папки установки, т.к. PyCharm постоянно обновляется и указанная версия в будущем станет не правильной.

Установка PyCharm в Ubuntu

Скачиваем установщик PyCharm Community для Linux с официального сайта JetBrains. Очень хорошей практикой является проверка контрольных сумм, так что если умеете, не ленитесь с проверкой.

Распаковываем архив с PyCharm и переименовываем папку с программой в pycharm-community , убрав версию из названия.

Теперь в директории

/.local (Ctrl + H — Показ скрытый файлов), создаем папку opt , куда и перемещаем pycharm-community . В результате по пути /.local/opt/pycharm-community должны размещаться папки bin , help и т.д. Таким образом PyCharm будет находится в своём скромном месте и никому не будет мешать.

Далее выполняем команды в терминале:

Производим установку. И очень важно в конце не забыть создать desktop файл для запуска PyCharm. Для этого в Окне приветствия в нижнем правом углу нажимаем на ConfigureCreate Desktop Entry.

Создание desktop файла

Установка PyCharm в Ubuntu из snap-пакета

PyCharm теперь можно устанавливать из snap-пакета. Если вы используете Ubuntu 16.04 или более позднюю версию, можете установить PyCharm из командной строки.

Использование VirtualEnv и Pip в PyCharm

Поддержка Pip и Virtualenv в PyCharm появилась уже довольно давно. Иногда конечно возникают проблемы, но взаимодействие работает в основном стабильно.

Рассмотрим два варианта работы с виртуальными окружениями:

  1. Создаём проект со своим собственным виртуальным окружением, куда затем будут устанавливаться необходимые библиотеки;
  2. Предварительно создаём виртуальное окружение, куда установим нужные библиотеки. И затем при создании проекта в PyCharm можно будет его выбирать, т.е. использовать для нескольких проектов.

Первый пример: использование собственного виртуального окружения для проекта

Создадим программу, генерирующую изображение с тремя графиками нормального распределения Гаусса Для этого будут использоваться библиотеки matplotlib и numpy, которые будут установлены в специальное созданное виртуальное окружение для программы.

Запускаем PyCharm и окне приветствия выбираем Create New Project.

В мастере создания проекта, указываем в поле Location путь расположения создаваемого проекта. Имя конечной директории также является именем проекта. В примере директория называется ‘first_program’.

Далее разворачиваем параметры окружения, щелкая по Project Interpreter. И выбираем New environment using Virtualenv. Путь расположения окружения генерируется автоматически. В Windows можно поменять в пути папку venv на Envs , чтобы команда workon находила создаваемые в PyCharm окружения. Ставить дополнительно галочки — нет необходимости. И нажимаем на Create.

Настройка первой программы в PyCharm

Теперь установим библиотеки, которые будем использовать в программе. С помощью главного меню переходим в настройки FileSettings. Где переходим в Project: project_nameProject Interpreter.

Чистое окружение у проекта

Здесь мы видим таблицу со списком установленных пакетов. В начале установлено только два пакета: pip и setuptools.

Справа от таблицы имеется панель управления с четырьмя кнопками:

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

Для добавления (установки) библиотеки в окружение нажимаем на плюс. В поле поиска вводим название библиотеки. В данном примере будем устанавливать matplotlib. Дополнительно, через Specify version можно указать версию устанавливаемого пакета и через Options указать параметры. Сейчас для matplotlib нет необходимости в дополнительных параметрах. Для установки нажимаем Install Package.

Установка библиотеки matplotlib

После установки закрываем окно добавления пакетов в проект и видим, что в окружение проекта добавился пакет matplotlib с его зависимостями. В том, числе был установлен пакет с библиотекой numpy. Выходим из настроек.

Теперь мы можем создать файл с кодом в проекте, например, first.py. Код программы имеет следующий вид:

Для запуска программы, необходимо создать профиль с конфигурацией. Для этого в верхнем правом углу нажимаем на кнопку Add Configuration. . Откроется окно Run/Debug Configurations, где нажимаем на кнопку с плюсом (Add New Configuration) в правом верхнем углу и выбираем Python.

Далее указываем в поле Name имя конфигурации и в поле Script path расположение Python файла с кодом программы. Остальные параметры не трогаем. В завершение нажимаем на Apply, затем на OK.

Создание конфигурации для Python программы

Теперь можно выполнить программу и в директории с программой появится файл gauss.png :

Графики нормального распределение гаусса

Второй пример: использование предварительно созданного виртуального окружения

Данный пример можно использовать во время изучения работы с библиотекой. Например, изучаем PySide2 и нам придется создать множество проектов. Создание для каждого проекта отдельного окружения довольно накладно. Это нужно каждый раз скачивать пакеты, также свободное место на локальных дисках ограничено.

Более практично заранее подготовить окружение с установленными нужными библиотеками. И во время создания проектов использовать это окружение.

В этом примере мы создадим виртуальное окружения PySide2, куда установим данную библиотеку. Затем создадим программу, использующую библиотеку PySide2 из предварительно созданного виртуального окружения. Программа будет показывать метку, отображающую версию установленной библиотеки PySide2.

Начнем с экран приветствия PyCharm. Для этого нужно выйти из текущего проекта. На экране приветствия в нижнем правом углу через ConfigureSettings переходим в настройки. Затем переходим в раздел Project Interpreter. В верхнем правом углу есть кнопка с шестерёнкой, нажимаем на неё и выбираем Add. , создавая новое окружение. И указываем расположение для нового окружения. Имя конечной директории будет также именем самого окружения, в данном примере — pyside2 . В Windows можно поменять в пути папку venv на Envs , чтобы команда workon находила создаваемые в PyCharm окружения. Нажимаем на ОК.

Создание окружения для PySide2

Далее в созданном окружении устанавливаем пакет с библиотекой PySide2, также как мы устанавливали matplotlib. И выходим из настроек.

Теперь мы можем создавать новый проект использующий библиотеку PySide2. В окне приветствия выбираем Create New Project.

В мастере создания проекта, указываем имя расположения проекта в поле Location. Разворачиваем параметры окружения, щелкая по Project Interpreter, где выбираем Existing interpreter и указываем нужное нам окружение pyside2 .

Создание нового проекта использующего библиотеку PySide2

Для проверки работы библиотеки создаем файл second.py со следующий кодом:

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

Заключение

У меня нет богатого опыта программирования на Python. И я не знаком с другими IDE для Python. Поэтому, возможно, данные IDE также умеют работать с Pip и Virtualenv. Использовать Pip и Virtualenv можно в командой строке или в терминале. Установка библиотеки через Pip может завершиться ошибкой. Есть способы установки библиотек без Pip. Также создавать виртуальные окружения можно не только с помощью Virtualenv.

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *