Edit configuration pycharm что делать
Advanced configuration
Besides the standard options available, PyCharm enables you to perform low-level configuration of the underlying platform and the Java runtime.
This may lead to unexpected problems and make your PyCharm installation inoperable if you are not sure what you are doing. Contact JetBrains Support for instructions regarding the options and values that might help you with whatever issue you are trying to solve.
JVM options
PyCharm runs on the Java Virtual Machine (JVM), which has various options that control its performance. The default options used to run PyCharm are specified in the following file:
Do not change JVM options in the default file, because it is replaced when PyCharm is updated. Moreover, in case of macOS, editing this file violates the application signature.
Configure JVM options
Do one of the following to create a copy of the default file with JVM options in the configuration directory that will override the original file:
If you cannot start PyCharm, manually copy the default file with JVM options to the PyCharm configuration directory.
If you do not have write access to the PyCharm configuration directory, you can add the PYCHARM_VM_OPTIONS environment variable to specify the location of the file with your preferred JVM options. This file will override both the original default file and the copy located in the PyCharm configuration directory.
Common options
The default values of the JVM options should be optimal in most cases. The following are the most commonly modified ones:
For more information about the available JVM options, see the java reference for Windows or macOS/Linux.
Platform properties
PyCharm enables you to customize various platform-specific properties, such as the path to user-installed plugins and the maximum supported file size. The default properties used to run PyCharm are specified in the following file:
Do not change platform properties in the default file, because it is replaced when PyCharm is updated. Moreover, in case of macOS, editing this file violates the application signature.
Configure platform properties:
Do one of the following to create an empty idea.properties file in the configuration directory that will override the values from the original file:
If you cannot start PyCharm, manually create an empty idea.properties file in the PyCharm configuration directory.
If you do not have write access to the PyCharm configuration directory, you can add the PYCHARM_PROPERTIES environment variable to specify the location of the idea.properties file. The properties in this file will override the corresponding properties in both the original default file and the one located in the PyCharm configuration directory.
Common properties
Users often change the location of the default IDE directories. For more information, see Change the location of IDE directories.
Limits that can affect performance:
PyCharm provides a number of other properties that define interaction with the environment (window managers, launchers, the file system, and so on). Most of them act like hidden settings (in the sense that they are not evidently exposed), which you may need to enable or disable in certain cases. Change these properties only if advised by JetBrains Support.
pycharm run/debug configuration. Примеры конфигураций
12 февраля 2014 г. 7:50
Конфигурации бывают нескольких видов. В моей практике распространены две:
Расмотрим в отдельности.
Запуск Django приложения в PyCharm (Пример конфигурации Django server)
Если у меня открыть настройки, то он будут такими:
Атоматически распознать Django server и проставить настройки помогает структура папок проекта. У меня она выглядит следующим образом:
Пример manage.py
Пример settings.py
Пример рабочего проекта
Для наглядности я подготовил рабочий демонстрационный проект, который вы можете скачать для наглядности:
По идее, загрузив пример проекта с виртуальным окружением, и открыв его через меню «File \ Open. «, PyCharm автоматически определит Django Server конфигурацию и вы сразу сможете запустить проект. Не забудьте только создать базу данных и применить миграции.
Пример простой конфигурации python-скрипта
Передо мной встала задача: написать скрипт оповещения клиентов об скором истечении срока действия услуг. Запуск скрипта должен производиться из консоли для того, чтобы его можно было добавить в cron. Решением этой задачи служит использование management команды.
Скрипт я написал: теперь самое время его протестировать и отладить в случае необходимости. И чтобы это было легче проводить, можно воспользоваться debug-ом в самом PyCharm-е. Для этого нужно добавить необходимую конфигурацию.
Добавить в PyCharm конфигурацию запуска обычного python скрипта достаточно просто: в списке конфигураций выбираем «Edit Configurations. » (на рисунке выделено синим цветом).
Затем щёлкаем по зелёному плюсику (выделено синей рамкой) и выбираем python:
А затем проделываем несколько нехитрых действий:
Нажимаем окей и можно дебажить!
Запуск Django-Shop приложения в PyCharm
Для начала откроем терминал и склонируем проект с github:
Далее выполним специфичные команды для запуска Django Shop демо-примера (для каждого проекта свои команды по запуску!):
В общем случае для любого проекта нужно:
И наконец, запускаем проект:
Если в терминале получилось запустить проект, то переходим к его запуску в PyCharm. Для этого открываем в PyCharm-е наш проект:
Теперь проверим правильно ли выбрано виртуальное окружение для проекта. Переходим в Project Interpreter :
/.virtualenvs/django-shop было установлено виртуальное окружение для проекта, поэтому проверьте, чтобы в поле Project Interpreter путь совпадал: 2.7.6 virtualenv at
Теперь закрываем окно настроек, и последнее что нам осталось сделать, это добавить конфигурацию запуска проекта. Для этого щёлкаем 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.
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
Once you save a temporary configuration, it becomes permanent and it is recorded in a separate XML file in the
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.
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.
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.
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
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
Specify the run/debug configuration name in the Name field. This name will be shown in the list of the available run/debug configurations.
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
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.
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 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
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.
In this field, specify parameters to be passed to the Python script.
When specifying the script parameters, follow these rules:
Use spaces to separate individual script parameters.
If script parameter includes double quotes, escape the double quotes with backslashes, for example:
In this field you can add a macros to pass various project- or context-specific values when running a run/debug configuration. Click + and select one of the available macros from the list. See Adding macros to run/debug configuration for more details.
This field shows the list of environment variables. If the list contains several variables, they are delimited with semicolons.
By default, the field contains the variable PYTHONUNBUFFERED set to 1. To fill in the list, click the browse button, or press Shift+Enter and specify the desired set of environment variables in the Environment Variables dialog.
You might want to populate the list with the variables stored as a series of records in a text file, for example:
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.
Specify a directory to be used by the running task.
When this field is left blank, the bin directory of the PyCharm installation will be used.
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;
Emulate terminal in output console
Note that emulating terminal in the output console differs from running the Terminal that is a separate tool window used for running system shell commands.
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..
Run options : Use this field to specify the Docker command-line options.
This field only appears when a Docker Compose-based remote interpreter is selected.
Commands and options
You can use the following commands of the Docker Compose Command-Line Interface:
up — Builds, creates, starts, and attaches to containers for a service.
run — Runs a one-time command against a service. See the reference docs.
exec — Runs arbitrary commands in your services.
You can expand this field to preview the complete command string.
Example: if you enter the following combination in the Commands and options field:
the preview output should looks as follows:
Работа в IDE PyCharm (FAQ) + полезные фишки
Талантливые ребята из JetBrains разработали одну из наиболее используемых IDE в мире для этого языка программирования.
В начале 2019 года компания JetBrains опросила почти 7000 разработчиков. 42% опрошенных, которые пишут на Python, выбрали PyCharm как основную IDE для своей работы.
PyCharm кроссплатформенна и совместима с Windows, Linux и MacOS. Она поддерживает, как вторую, так и третью версию Питона и, кроме всего прочего, имеет красивый и функциональный UI.
Инструменты и функции, предоставляемые этой интегрированной средой, помогают Python-программистам быстро и эффективно писать код, синхронизироваться с системой контроля версий, использовать фреймворки и плагины, позволяя при этом настроить интерфейс так, как удобно самому пользователю и даже дают возможность дополнительного расширения IDE.
В PyCharm, конечно же, есть встроенный анализатор кода, который действительно помогает при его написании. Благодаря анализатору можно весьма комфортно перемещаться по проекту, использовать быстрый поиск, а также исправлять ошибки, которые PyCharm любезно подсвечивает и подробно описывает.
Тут реализованы системы автодополнения и контроля качества кода в соответствии со стандартом PEP8. Всё для того, чтобы сделать текст ваших программ красивее, чище и структурированнее.
В интегрированной среде от JetBrains поддерживаются основные современные Python-фреймворки для веб-разработки, в ней вы сможете работать с Jupyter-notebook, подключать Anaconda, а также прочие библиотеки для научных вычислений и Data Science. Но, как говорится — «И это ещё не всё!». Помимо, собственно, питона, PyCharm отлично ладит и с другими языками программирования — JS, TypeScript-а, SQL или шаблонизаторами.
Системные требования
Официальные системные требования последней версии PyCharm выглядят так:
RAM: не менее 2 ГБ, но рекомендуется 8 ГБ;
Место на диске: установка потребует 2,5 ГБ, рекомендуется использование SSD;
Разрешение экрана : не менее 1024×768 пикселей;
Python: Python 2.7, Python 3.5 или более поздняя версия;
При этом разработчики обращают внимание пользователей macOS и Linux на то, что JBR 11 поставляется в комплекте с PyCharm, и дополнительно устанавливать Java им не нужно.
В самих системных требованиях нет ничего особенного, однако хочется отметить, что IDE прекрасно себя чувствует и на Windows 7, а к рекомендациям по поводу 8 ГБ оперативной памяти и использования SSD стоит тщательным образом прислушаться, не прогадаете 😉.
Как установить
Процесс установки вкратце описан на официальном сайте для каждой из поддерживаемых ОС:
На Windows
На Mac OS
На Linux
Подготовка к работе и настройка
Перед тем, как приступить к разработке в PyCharm, вам нужно создать проект, поскольку все дальнейшие манипуляции будут происходить именно в нём и на его основе.
Чтобы начать новый проект, нажмите New Project и придумайте ему имя. Теперь можно приступить к настройке.
Настройки интерфейса
Несмотря на то, что разработчики из JetBrains начинали свой путь в России, смена языка интерфейса в среде разработки не предусмотрена, поэтому к вашим услугам будет лишь родной язык Уильяма Шекспира.
Зато вы можете изменить сами шрифты и их размеры, пройдя по пути:
Поменять цветовую схему UI:
И сконфигурировать множество других аспектов, вроде общих настроек, конфигураций прокрутки, настроек цвета для каждого доступного языка и так далее. Для всего этого есть редактор:
Настройка интерпретатора
Для использования установленного интерпретатора, выберите его в настройках:
💭 Если PyСharm не видит интерпретатор, попробуйте добавить его вручную. Для этого:
Настройка виртуального окружения
Если по долгу программистской службы вам приходится работать с несколькими проектами, то определенно не помешает настройка и подключение виртуального окружения.
Venv — это, грубо говоря, директория, содержащая ссылку на интерпретатор и набор установленных библиотек. Виртуальное окружение “изолирует” ваши проекты, и помогает, в частности, не запутаться в разных версиях библиотек, адаптированных для каждого из них по отдельности.
Если вы настроили виртуальное окружение заранее, PyCharm покажет уведомление, в котором предложит использовать его в проекте. Если уведомления нет, вы всегда можете настроить и изменить его вручную в настройках:
Также в этом меню можно создать виртуальные окружения с нуля. Для этого:
Venv создано и готово к работе 👌.
Окружение Pipenv создается аналогичным образом
Запуск скриптов в консоли
Чтобы запустить код в PyCharm, нужно выбрать интерпретатор в настройках (как это сделать я писал чуть выше).
Также, перед запуском своего кода в PyCharm необходимо добавить конфигурацию (чтобы IDE понимал, какой файл ему запускать и по каким правилам). Изначально, если проект новый, конфигурации нет, и кнопка запуска не активна.
Чтобы запустить код в новом проекте, зайдите в
или выполните комбинацию:
Откроется диалоговое окно в выбором файла, который необходимо запустить.
После запуска, откроется терминал, в котором вы увидите результат выполнения своего скрипта и сообщение о том, что процесс завершился с кодом 0 (0 означает успешное завершение).
Далее, когда конфигурация создана и сохранена, запускать свой код на выполнения можно комбинацией:
☝️ Если скрипт не запускается, возможно вы не сохранили конфигурацию или PyCharm не видит интерпретатор. Настроить или создать конфигурацию можно в меню » Edit Configurations.. «, которое находится сверху справа, около кнопки «Run».
Есть еще один способ запуска кода:
💁♂️ В целях обучение, вам может понадобиться быстро писать и проверять Python-инструкции. Для этого в PyCharm-е реализован интерактивный режим (по аналогии с IDLE ). Чтобы его вызвать, достаточно нажать на » Python Conole » внизу слева.
Отладчик (debugger) в Pycharm
Отладка — чрезвычайно полезный инструмент. С помощью него можно пошагово исполнять программный код. Интерпретатор переходит в особый режим, фиксируя на каждом этапе выполнения текущее состояние программы. Т.е. для каждой строки кода вам будет представлен мини-отчёт, в котором можно посмотреть актуальные значения всех переменных и проследить таким образом весь процесс их изменения.
Находясь в руках опытного разработчика, отладчик сокращает время поиска ошибок на порядки.
Для старта отладки, нужно поставить так называемую точку останова. Это красный кружок напротив строки кода.
Вы можете установить её где захотите, но чаще всего точку следует ставить там, где интерпретатор увидел ошибку.
Для запуска кода в режиме отладки нажмите на значок в «жука» в левом верхнем углу:
Или выполните комбинацию:
Все варианты навигации в режиме отладки можно посмотреть в окне «Debugger»:
Для каждой кнопки существует свой hotkey — чтобы увидеть его, достаточно навести курсор на нужную кнопку.
Deploy на удаленный хост
Развернуть и отправить код на сервер возможно прямиком из PyCharm.
Инструмент не доступен в бесплатной комьюнити-версии
Чтобы добавить удалённый сервер, первым делом перейдём в:
Теперь можно производить deploy:
Макросы
Макросы, как и многие другие вещи нужны исключительно для облегчения нашей с вами жизни. Они позволяют автоматизировать ряд повторяющихся процедур, которые вы чаще всего выполняете во время написания кода. Вы можете записывать, редактировать и воспроизводить макросы, назначать им ярлыки и даже делиться ими.
Чтобы создать или настроить свой собственный макрос, вам нужно выбрать:
Полезные хоткеи и фишки
⚡ Как поменять цвет консоли в pycharm. Поменять цвет консольного бэкграунда или шрифтов предельно просто: для этого нужно всего лишь зайти в настройки цветовой схемы и изменить их так, как того пожелает ваш внутренний дизайнер:
⚡ Поиск по всему проекту.
⚡ Хоткеи по запуску и дебаггингу. С помощью комбинации клавиш Shift + F10 можно запустить ваш проект, а нажав Shift + F9 — начать его отладку.
Повторив то же самое действие на том же самом месте, вы выполните раскомментирование кода.
⚡ Некоторые горячие клавиши.
ТОП 7 полезных плагинов для Pycharm
Меню установки плагинов находится в:
Для установки плагина достаточно написать его название в строке поиска, найти плагин и нажать » Install «.
⭐ Вот список полезных плагинов, которые стоит установить:
Другие полезные плагины:
Что делать, если PyCharm не видит модули Python?
Если у вас возникла подобная проблема, то в первую очередь стоит проверить настройки интерпретатора.
Вариант №1 — сброс настроек и выборе новой версии интерпретатора. Настройки находятся тут: