- Configure a virtual environment
- Create a virtual environment
- Set an existing virtual environment
- Create a virtual environment using the project requirements
- pycharm run/debug configuration. Примеры конфигураций
- Запуск Django приложения в PyCharm (Пример конфигурации Django server)
- Пример manage.py
- Пример settings.py
- Пример рабочего проекта
- Пример простой конфигурации python-скрипта
- Запуск Django-Shop приложения в PyCharm
- Run/debug configurations
- Create permanent run/debug configurations
- Save a temporary configuration as permanent
- Create a run/debug configuration from a template
- Share run/debug configurations
- Run/debug configuration templates
- Configure the default values for a template
- Compound run/debug configurations
- Create a compound run/debug configuration
- Run/debug configuration folders
- Create a folder for run/debug configurations
- Run/Debug configurations in the Services tool window
- Add Run/Debug configurations to the Services window
- Run/Debug configuration parameters
Configure a virtual environment
PyCharm makes it possible to use the virtualenv tool to create a project-specific isolated virtual environment . The main purpose of virtual environments is to manage settings and dependencies of a particular project regardless of other Python projects. virtualenv tool comes bundled with PyCharm, so the user doesn’t need to install it.
For Python 3.3+ the built-in venv module is used, instead of the third-party virtualenv utility.
Create a virtual environment
Ensure that you have downloaded and installed Python on your computer.
Do one of the following:
Click the Python Interpreter selector and choose Add Interpreter .
Press Ctrl+Alt+S to open the project Settings/Preferences and go to Project
| Python Interpreter . Then click the icon and select Add .
In the left-hand pane of the Add Python Interpreter dialog, select Virtualenv Environment . The following actions depend on whether the virtual environment existed before.
If New environment is selected:
Specify the location of the new virtual environment in the text field, or click and find location in your file system. Note that the directory where the new virtual environment should be located, must be empty!
Choose the base interpreter from the list, or click and find a Python executable in the your file system.
If PyCharm detects no Python on your machine, it provides two options: to download the latest Python versions from python.org or to specify a path to the Python executable (in case of non-standard installation).
Select the Inherit global site-packages checkbox if you want that all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.
Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.
If Existing environment is selected:
Expand the Interpreter list and select any of the existing interpreters. Alternatively, click and specify a path to the Python executable in your file system, for example, C:\Python36\python.exe .
Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.
Click OK to complete the task.
If PyCharm warns you about an Invalid environment , the specified Python binary cannot be found in the file system, or the Python version is not supported. Check the Python path and install a new version, if needed.
You can create as many virtual environments as required. To easily tell them from each other, use different names.
Set an existing virtual environment
- Press Ctrl+Alt+S to open the IDE settings and select Project
Expand the list of the available interpreters and click the Show All link. Alternatively, click the icon and select Show All .
Virtual environments are marked with .
Select the target environment from the list and click OK to confirm your choice.
PyCharm can create a virtual environment for your project based on the project requirements.
Create a virtual environment using the project requirements
Open any directory with your source files that contains the requirements.txt or setup.py file: select File | Open from the main menu and choose the directory.
If no virtual environment has been created for this project, PyCharm suggests creating it:
Keep the suggested options, or specify the environment location or base Python interpreter. Click OK to complete the task.
Once you click OK , PyCharm creates an environment and installs all the required packages. On the completion, see the notification popup:
Note that if you ignore a suggestion to create a virtual environment, PyCharm won’t create a Python interperter for your project. So, any time when you open a .py file, you’ll see the warning with the options for configuring a project interpreter:
This approach is particularly helpful when you want to upgrade a version of Python your environment is based on, for example, from 3.5 to 3.9. You can specify a new base interpreter and use requirements.txt to ensure all the needed packages are installed.
For any of the configured Python interpreters (but Docker-based), you can:
Once you have create a new virtual environment, you can reuse it for your other projects. Learn more how to setup an existing environment as a Python interpreter.
Источник
pycharm run/debug configuration. Примеры конфигураций
12 февраля 2014 г. 3:50
Конфигурации бывают нескольких видов. В моей практике распространены две:
- Django server — для запуска самого сайта.
- Python — для выполнения различных скриптов, у меня чаще всего management-команд.
Расмотрим в отдельности.
Запуск Django приложения в PyCharm (Пример конфигурации Django server)
У меня лично этот процесс происходит автоматически, то есть при открытии папки проекта (через меню «File \ Open. «) PyCharm самостоятельно создаёт конфигурацию Django server с необходимыми настройками:
Если у меня открыть настройки, то он будут такими:
Атоматически распознать Django server и проставить настройки помогает структура папок проекта. У меня она выглядит следующим образом:
Пример manage.py
Пример settings.py
Пример рабочего проекта
Для наглядности я подготовил рабочий демонстрационный проект, который вы можете скачать для наглядности:
По идее, загрузив пример проекта с виртуальным окружением, и открыв его через меню «File \ Open. «, PyCharm автоматически определит Django Server конфигурацию и вы сразу сможете запустить проект. Не забудьте только создать базу данных и применить миграции.
Пример простой конфигурации python-скрипта
Передо мной встала задача: написать скрипт оповещения клиентов об скором истечении срока действия услуг. Запуск скрипта должен производиться из консоли для того, чтобы его можно было добавить в cron. Решением этой задачи служит использование management команды.
Скрипт я написал: теперь самое время его протестировать и отладить в случае необходимости. И чтобы это было легче проводить, можно воспользоваться debug-ом в самом PyCharm-е. Для этого нужно добавить необходимую конфигурацию.
Добавить в PyCharm конфигурацию запуска обычного python скрипта достаточно просто: в списке конфигураций выбираем «Edit Configurations. » (на рисунке выделено синим цветом).
Затем щёлкаем по зелёному плюсику (выделено синей рамкой) и выбираем python:
А затем проделываем несколько нехитрых действий:
- Вписываем имя конфигурации в поле «Name». В моём случае client_notifications, и у меня часто имя конфигурации совпадает с именем самого скрипта — так удобно.
- Указываем полный путь до скрипта в «Script». Да, на скриншоте путь начинается с E 🙂 Раньше под виндой сидел, теперь давно уже на Linux-е.
- Пишем параметры скрипта в «Script parameters». Имя файла моего скрипта client_notifications, поэтому его и пишем.
Нажимаем окей и можно дебажить!
Что касается поля «Interpreter options» — там указываются параметры самого интерпретатора python. По сути они вставляются между python и manage.py.
А «Working directory» можно не трогать. В данном случае он ни на что не влияет.
Запуск Django-Shop приложения в PyCharm
Разберём более сложный пример запуска конфигурации: попробуем запустить скаченный с какого-нибудь репозитория (напр., github) проект на Django. В качестве примера выберем Django Shop — платформа для создания интернет-магазина.
Для начала откроем терминал и склонируем проект с github:
Далее выполним специфичные команды для запуска Django Shop демо-примера (для каждого проекта свои команды по запуску!):
В общем случае для любого проекта нужно:
- Создать виртуальное окружение командой virtualenv .
- Войти в виртуальное окружение командой source .
- Установить зависимости (чаще всего они перечислены в файле requirements.txt) командой pip install .
И наконец, запускаем проект:
Если в терминале получилось запустить проект, то переходим к его запуску в PyCharm. Для этого открываем в PyCharm-е наш проект:
Нам важно, чтобы мы смогли просматривать в PyCharm все файлы проекта, склонированного с github, поэтому выбираем корневую папку проекта django-shop .
Теперь нам нужно добавить поддержку Django для приложения. Для этого выбираем в меню: «File \ Settings . «:
В этом окне нужно настроить Django project root . Эту директорию можно выбирать такую, в которой лежит manage.py. После выбора директории вы заметите, что PyCharm сам попытался определить местонахождение manage.py и settings.py. Давайте ему поможем, определив точное месторасположение этих файлов. В случае с Django Shop settings.py лежит в папке myshop, поэтому щёлкаем на значок «Три точки» в соответствующем поле для открытия диалогового окна и находим наш settings.py.
Обратите внимание, что мы также добавили переменную окружения DJANGO_SHOP_TUTORIAL в поле Environment variables . Чуть ниже вы увидите, что переменные окружения также добавляются при создании конфигурации, и для Django Shop переменную DJANGO_SHOP_TUTORIAL нужно задавать в двух местах, потому что этот проект требует обязательного наличия DJANGO_SHOP_TUTORIAL в переменных окружения. А так как запуск management команд через PyCharm (гор. клавиша Ctrl + Alt + R) таких, как makemigrations или migrate , происходит в отдельной конфигурации, поэтому без указания DJANGO_SHOP_TUTORIAL команды не смогут запуститься и выведут такую ошибку django.core.exceptions.ImproperlyConfigured: Environment variable DJANGO_SHOP_TUTORIAL is not set :
Поэтому поставим DJANGO_SHOP_TUTORIAL=commodity .
Теперь проверим правильно ли выбрано виртуальное окружение для проекта. Переходим в Project Interpreter :
/.virtualenvs/django-shop было установлено виртуальное окружение для проекта, поэтому проверьте, чтобы в поле Project Interpreter путь совпадал: 2.7.6 virtualenv at
/.virtualenvs/django-shop . Найти этот путь можно щёлкнув на крайнюю справа стрелочку вниз этого поля. Если в списке нет пути до виртуального окружения, то можно его вручную добавить, щёлкнув на значок шестерёнки (правее стрелки влево):
Теперь закрываем окно настроек, и последнее что нам осталось сделать, это добавить конфигурацию запуска проекта. Для этого щёлкаем Edit Configuration :
И, щёкнув на плюсик, выбираем Django Server:
Теперь остаётся заполнить Environment variables по необходимости:
Имейте ввиду, что, если у вас в переменных окружения DJANGO_SETTINGS_MODULE=settings :
Источник
Run/debug configurations
PyCharm uses run/debug configurations to run, debug, and test your code. Each configuration is a named set of startup properties that define what to execute and what parameters and environment should be used.
When you create a new configuration for a specific kind of executable context, you create it from one of the dedicated configuration templates, which implement the startup logic, define the list of parameters and their default values. The list of available templates is predefined in the installation and can only be extended via plugins. However, you can edit default values of parameters in each template to streamline the creation of new configurations.
With different startup properties, you can define different ways that PyCharm uses to execute your script. For example, you can execute the same code with different Python interpreters, providing various sets of environment variables, and getting input values from alternative files.
If the Navigation bar is visible ( View | Appearance | Navigation Bar ), you can access all available run/debug configurations from the selector on the toolbar.
Run/debug configurations can be created as:
- Temporary — created every time you run or debug functions or tests.
The maximum number of temporary configurations is 5. The older ones are automatically deleted when new ones are added. If necessary, you can increase this limit in Settings/Preferences | Advanced Settings | IDE | Temporary Run/Debug configurations limit .
Permanent — created explicitly from a template or by saving a temporary configuration. Permanent configurations remain as part of your project until you remove them.
So whenever you run/debug or test your code, PyCharm either uses an existing permanent run/debug configuration or creates a new temporary one.
Permanent configurations have opaque icons while the icons of temporary configurations are semi-transparent.
Create permanent run/debug configurations
PyCharm provides the following ways to create a permanent run/debug configuration:
Create from a template or copy an existing configuration.
Save a temporary configuration as permanent
Select a temporary configuration in the run/debug configuration switcher and then click Save Configuration .
Once you save a temporary configuration, it becomes permanent and it is recorded in a separate XML file in the
/.idea/ directory. For example, MyProject/.idea/Car.xml .
Alternatively, select a temporary configuration in the Run/debug configurations dialog and click on the toolbar.
PyCharm provides run/debug configuration templates for different languages, tools, and frameworks. The list of available templates varies depending on the installed and enabled plugins.
Create a run/debug configuration from a template
Open the Run/Debug Configuration dialog in one of the following ways:
Select Run | Edit Configurations from the main menu.
With the Navigation bar visible ( View | Appearance | Navigation Bar ), choose Edit Configurations from the run/debug configuration selector.
Press Alt+Shift+F10 and then press 0 .
In the Run/Debug Configuration dialog, click on the toolbar or press Alt+Insert . The list shows the run/debug configuration templates.
Select the desired template. If you are not sure which template to choose, refer to Run/debug configurations dialog for more information on particular templates.
Specify the run/debug configuration name in the Name field. This name will be shown in the list of the available run/debug configurations.
Select Allow parallel run if you want to allow multiple instances of the configuration to run at the same time. If this option is disabled, attempting to re-run the configuration will terminate the active session.
In the Before launch section, define whether you want to perform any specific actions before launching the application, for example, execute some tools or scripts prior to launching the run/debug configuration.
For information on particular Before launch activities, refer to Before launch
Apply the changes and close the dialog.
Share run/debug configurations
If you are working in a team, you might want to share your run/debug configurations so that your teammates could run the application using the same configuration or enable them to remotely attach to the process you are running.
For these purposes, PyCharm provides a mechanism to store your run/debug configurations as project files and share them through VCS. The same mechanism can also be used when you want to send your configuration as a file to someone else. This saves a lot of time as run/debug configurations sometimes get sophisticated, and keeping them in sync manually would be tedious and error-prone.
Legacy .ipr -based projects do not support individual run/debug configurations. With legacy projects, you can only share all configurations at once by adding the .ipr file to the VCS.
From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .
Select the run/debug configuration you want to share, enable the Store as project file option, and specify the location where the configuration file will be stored.
If compatibility with PyCharm 2019.3 and earlier is required, store the file in the default location.
(Optional) If the .idea directory is added to VCS ignored files, the .idea/runConfigurations subfolder will be ignored, too. If you use Git for your project, you can share .idea/runConfigurations only and leave .idea ignored by modifying .gitignore as follows:
Turning on the Store as project file option does not submit anything to the VCS for you. For run/debug configurations to make their way to a shared repository, you have to check them in like other versioned files.
To learn how to import run/debug configurations from VCS, refer to the Version control section.
Run/debug configuration templates
Each type of run/debug configuration is a template that you can edit, so the next time you create a new configuration of that type, its parameters already have the desired values.
Changing the default values of a template does not affect already existing run/debug configurations.
Do not set up a working directory for the default Run/Debug Configurations listed under the Templates node. This may lead to unresolved targets in newly created Run/Debug Configurations.
Configure the default values for a template
From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .
In the left-hand pane of the run/debug configuration dialog, click Edit configuration templates .
In the Run/Debug Configuration Templates dialog that opens, select a configuration type.
Specify the desired default parameters and click OK to save the template.
Compound run/debug configurations
Suppose you would like to launch multiple run/debug configurations simultaneously. For example, you may want to run several configurations of different types or a group of test configurations. You can configure this behavior with a compound run/debug configuration.
The order of execution is not guaranteed. If you need run/debug configurations to run sequentially, define the sequence in the Before launch area of the run/debug configuration that should run last.
Create a compound run/debug configuration
From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .
In the Run/Debug Configurations dialog, click or press Alt+Insert , then select Compound .
Specify the run/debug configuration name in the Name field. This name will be shown in the list of the available run/debug configurations.
Select Store as project file to make this run/debug configuration available to other team members .
To include a new run/debug configuration into the compound configuration, click Add and select the desired one from the list.
Apply the changes.
Run/debug configuration folders
When there are many run/debug configurations of the same type, you can group them in folders so they become easier to distinguish visually.
Once grouped, the run/debug configurations appear in the list under the corresponding folders.
Create a folder for run/debug configurations
From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .
In the Run/Debug Configurations dialog, select a configuration type and click on the toolbar. A new empty folder for the selected type is created.
Specify the folder name in the text field to the right or accept the default name.
Select the desired run/debug configurations and move them under the target folder.
Apply the changes. If a folder is empty, it will not be saved.
When you no longer need a folder, you can delete it Delete . The run/debug configurations grouped under this folder will be moved under the root of the corresponding run/debug configuration type.
Run/Debug configurations in the Services tool window
You can manage multiple run/debug configurations in the Services tool window. For example, you can start, pause, and stop several applications, track their status, and examine application-specific details.
Add Run/Debug configurations to the Services window
Select View | Tool Windows | Services from the main menu or press Alt+8 .
In the Services tool window, click Add service , then select Run Configuration Type .
Select a run/debug configuration type from the list to add all configurations of this type to the window.
Note that the tool window will only display the configuration types for which you have created one or more configurations.
Run/Debug configuration parameters
| Item | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| Script path/Module name | Click the list to select a type of target to run. Then, in the corresponding field, specify the path to the Python script or the module name to be executed. | ||||||||
| Parameters | |||||||||
| Environment | |||||||||
| Project | Click this list to select one of the projects, opened in the same PyCharm window , where this run/debug configuration should be used. If there is only one open project, this field is not displayed. | ||||||||
| Environment variables | |||||||||
| Python Interpreter | Select one of the pre-configured Python interpreters from the list. When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported. | ||||||||
| Interpreter options | In this field, specify the command-line options to be passed to the interpreter. If necessary, click , and type the string in the editor. | ||||||||
| Working directory | |||||||||
| Add content roots to PYTHONPATH | Select this checkbox to add all content roots of your project to the environment variable PYTHONPATH; | ||||||||
| Add source roots to PYTHONPATH | Select this checkbox to add all source roots of your project to the environment variable PYTHONPATH; | ||||||||
| Execution | |||||||||
| Emulate terminal in output console | |||||||||
| Run with Python console | Enables running your script or module with the Python console. | ||||||||
| Redirect input from | Enables redirecting data from a text file to standard input. Use this option if your script requires some input and you want to automatically submit the values instead of typing them in the Run console. To enable redirecting, select the checkbox and specify the path to the target text file. | ||||||||
| Docker container settings This field only appears when a Docker-based remote interpreter is selected for a project.. Click to open the dialog and specify the following settings: Publish all ports : Expose all container ports to the host. This corresponds to the option —publish-all . Port bindings : Specify the list of port bindings. Similar to using the -p option with docker run . Volume bindings : Use this field to specify the bindings between the special folders- volumes and the folders of the computer, where the Docker daemon runs. This corresponds to the -v option. See Managing data in containers for details. Environment variables : Use this field to specify the list of environment variables and their values. This corresponds to the -e option. Refer to the page ENV (environment variables) for details. Run options : Use this field to specify the Docker command-line options. Click to expand the tables. Click , , or to make up the lists. This field only appears when a Docker Compose-based remote interpreter is selected. You can use the following commands of the Docker Compose Command-Line Interface:
You can expand this field to preview the complete command string. Example: if you enter the following combination in the Commands and options field: up —build exec —user jetbrains the preview output should looks as follows: Источник | |||||||||