Script path pycharm что писать
Перейти к содержимому

Script path pycharm что писать

  • автор:

Run/Debug Configuration: Shell Script

The set of parameters in the dialog depends on the option you select under Execute :

Script file (a configuration to run a script file)

Script text (a configuration to run a single command)

Provide the path to the shell script file. Type the path manually or click and select the path in the dialog that opens.

Specify the options that you want to pass to the script when it is launched.

Provide the absolute path of a directory to run the script in.

Specify environment variables if you need them in the script. You can click to open the Environment Variables window where you can browse and copy existing variables or create your own.

Provide the path to the interpreter for running the script. Type the path manually or click and select the path in the dialog that opens.

Specify the options that you want to pass to the script interpreter.

Enter the text of the command to be run.

Provide the absolute path of a directory to run the command in.

Specify environment variables if you need them in the command. You can click to open the Environment Variables window where you can browse and copy existing variables or create your own.

Common settings

When you edit a run configuration (but not a run configuration template), you can specify the following options:

Specify a name for the run configuration to quickly identify it among others when editing or running.

Allow multiple instances

Allow running multiple instances of this run configuration in parallel.

By default, it is disabled, and when you start this configuration while another instance is still running, PyCharm suggests stopping the running instance and starting another one. This is helpful when a run configuration consumes a lot of resources and there is no good reason to run multiple instances.

Store as project file

Save the file with the run configuration settings to share it with other team members. The default location is .idea/runConfigurations . However, if you do not want to share the .idea directory, you can save the configuration to any other directory within the project.

By default, it is disabled, and PyCharm stores run configuration settings in .idea/workspace.xml .

Toolbar

The tree view of run/debug configurations has a toolbar that helps you manage configurations available in your project as well as adjust default configurations templates.

Create a run/debug configuration.

Delete the selected run/debug configuration. Note that you cannot delete default configurations.

Create a copy of the selected run/debug configuration. Note that you create copies of default configurations.

The button is displayed only when you select a temporary configuration. Click this button to save a temporary configuration as permanent.

Move into new folder / Create new folder. You can group run/debug configurations by placing them into folders.

To create a folder, select the configurations within a category, click , and specify the folder name. If only a category is in focus, an empty folder is created.

Then, to move a configuration into a folder, between the folders or out of a folder, use drag or and buttons.

To remove grouping, select a folder and click .

Click this button to sort configurations in the alphabetical order.

Before launch

In this area, you can specify tasks to be performed before starting the selected run/debug configuration. The tasks are performed in the order they appear in the list.

Click this icon to add one of the following available tasks:

Run External tool : select to run an external application. In the dialog that opens, select one or multiple applications you want to run. If it is not defined in PyCharm yet, add its definition. For more information, see External tools and External Tools.

Run Another Configuration : select to execute another run/debug configuration and wait until it finishes before starting the current configuration. If you want to run several configurations in parallel, use a compound run/debug configuration.

Launch Web Browser : select this option to have a browser started. In the dialog that opens, select the type of the browser and provide the start URL. Also, specify if you want the browser be launched with JavaScript debugger.

Run File Watchers : select this option to have PyCharm apply all the currently active File Watchers.

Run Grunt task : select this option to run a Grunt task.

In the Grunt task dialog that opens, specify the Gruntfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Grunt tool.

Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the grunt-cli package.

Run gulp task : select this option to run a Gulp task.

In the Gulp task dialog that opens, specify the Gulpfile.js where the required task is defined, select the task to execute, and specify the arguments to pass to the Gulp tool.

Specify the location of the Node.js interpreter, the parameters to pass to it, and the path to the gulp package.

Run npm script : select this option to execute an npm script.

In the NPM Script dialog that opens, specify the npm run/debug configuration settings.

Start React Native Bundler : select this option to run the bundler automatically, as part of a running or debugging session. By default, this is done through react-native start .

If your application uses Expo, you need to run the development server via the start npm task. To do that, click , then in the Configure React Native dialog, choose npm script and select start from the list.

If the Check errors checkbox is selected, the compiler will show all the errors and the run configuration will not start.

If the Check errors checkbox is cleared, the compiler will show all the detected errors but the run configuration still will be launched.

Generate CoffeeScript Source Maps : select this option to generate the source maps for your CoffeeScript sources. In the dialog that opens, specify where your CoffeeScript source files are located.

Run Remote External Tool : adds a remote SSH external tool.

Click this icon to remove the selected task from the list.

Click this icon to edit the selected task. Make the necessary changes in the dialog that opens.

Click these icons to move the selected task one line up or down in the list. The tasks are performed in the order that they appear in the list.

Select this checkbox to show the run/debug configuration settings prior to actually starting the run/debug configuration.

Activate tool window

By default this checkbox is selected and the Run or the Debug tool window opens when you start the run/debug configuration.

Otherwise, if the checkbox is cleared, the tool window is hidden. However, when the configuration is running, you can open the corresponding tool window for it yourself by pressing Alt+4 or Alt+5 .

Создание виртуальных окружений и установка библиотек для 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 с использованием сторонних библиотек.

Create a PyCharm configuration that runs a module a la "python -m foo"

My python entrypoint needs to be run as a module (not a script), as in:

The following does not work (and is not supposed to):

How can I create a run confirguration in pycharm that runs my code using the first invokation above?

5 Answers 5

In 2018.1 it is finally possible to specify the module name instead of the script path in the UI. There is a dropdown for changing it, to the left of the input field.

PyCharm Run Configuration

There is a workaround I use for my scripts, which do use relative imports.

Script path pycharm что писать

It will show you how to configure PyCharm to work with Python in a virtual environment. Also you will configure the requirements.txt.

Start PyCharm create a new project or clone it from your repository. As an example I created a file first_example.py to write inside the main. I specify that this is only an example and for reasons of brevity does not follow the structure of a Python project.

Install Python

First, make sure Python 3 is installed by running the following command:

If python 2 and 3 is installed, the output will be the installed version of python 2 and 3.

If python is not installed, run the command and choose version 3.6 for example¹:

Create virtualenv with:

It is possible to create virtualenv on the same directory or on a different directory. In this article I use the same directory as the project directory. In my case i call the directory “venv”, but we can use “any_name”:

If all went well you will have the folder venv in your project:

To activate virtual environment lunch:

The fact that there is venv in parenthesis means that all libraries will be installed in the virtual environment and will not “dirty” the global environment. For more information about the virtual environment read this https://docs.python.org/3/tutorial/venv.html.

Python Interpreter

If you can’t find the python interpreter in the previous window then you have to create or add it. Just go to File →Settings →Project →Python interpreter →Add.

In the Interpreter box is present the path of our virtual environment:

Click Ok and then on Apply, then we will see all the libraries installed in our virtual environment.

Executing a program in the virtual environment

Let’s consider the example first_example, go to Add Configuration…

A window will open. Click on the “+” in the upper left corner. Now we can configure our Python program ready to run. Enter the “Name” (first_example), set “Script path” to the file where the main is located. Then we should find the “Python interpreter” already configured, in any case, having added it we will find it in the dropdown menu. Note that the interpreter path is the one related to the virtual environment created!

Lunch simple program

Let’s consider the following code:

requirements.txt

If you share a project with other users using a build system or plan to copy the project to another location where an environment is to be restored, you must specify the external packages required by the project. The recommended approach is to use a requirements.txt file, which contains a list of pip commands and allows you to install the required versions of dependent packages.

We assume to install Pandas (data analysis and manipulation tool), we lunch:

Getting Started with PyCharm¶

This tutorial assumes you are familiar with the process of building Mantid (with separate source and build directories inside a root directory), and that you have built a working version. If you are unclear about this see here .

Setting up PyCharm on Windows¶

Once PyCharm is open, set up the project. Go to File->Open and select the root directory in which both your source and build directories reside.

Go to File->Settings , then under Project you will set two sub-menus Project Interpreter and Project Structure . The interpreter defines the python executable that will be used to run your code, and the structure menu allows you to decide which folders within the project to include and index.

In the Project Interpreter sub menu, at the top select the options button and click Add. , a new window should appear titled “Add Python Interpreter”. In the menu on the left, select “System Interpreter” (a version of Python with all the correct variables set already exists within Mantid). Click on the . to open a file browser, and navigate to;

This is the interpreter, so select “Ok” and apply the changes. This should bring up a list of all the packages associated to the interpreter. There should be many packages, however you should not see PyQt (but instead QtPy).

In the Project Structure sub menu you should see your root directory with the source/build directories both visible (if not, add them). The folder structure should be present in the centre of the window allowing you to mark folders orange (excluded) or blue (source). Source directories will be searched for python code.

Within the source directory add the following to your sources:

If you are writing scripts in any other directories, you can also mark them as sources. This helps PyCharm give better auto-complete and import suggestions during development.

Additionally, in the Mantid build directory add the following as source folders:

here we are setting up PyCharm for the Debug build, you would use /bin/Release instead if you are building mantid in release mode.

The environment needs to be set up before running the configuration. Follow the instructions below to use either the EnvFile plugin (recommended) or manual path setup.

NOTE : In some cases, imports in the code will still be highlighted red when they come from folders within the script/ folder, or from other folders entirely. To fix this simply add the relevant folder that contains the module you are importing in the same fashion as step 3 above.

Running Files in the Debugger with EnvFile extension¶

Running python code from within PyCharm which depends on the python API, or PyQt for example requires one extra step. Because the source root labelling from the previous section only affects PyCharm searching and not the run configuration, before running the file we must set up the run configuration correctly.

  1. Install the EnvFile plugin by Borys Pierov. The plugin can be installed in multiple ways:
    1. Open Settings(CTRL + SHIFT + S), to go Plugins and search for EnvFile . Install and restart PyCharm.
    2. Go to the plugin’s webpage, download and install it.

    For running the Workbench continue onto Workbench , and follow the instructions to set up the Script Path and Working Directory.

    Advantages of this approach:

    • You can have multiple instances of PyCharm running with environment configuration for separate repositories. This is otherwise not possible, as all PyCharm instances seem to share a parent process and environment. (as is the case of 11/01/2019, it might change in the future)
    • This makes possible switching projects for multiple repositories via the File > Open Recent … menu, as when the new project is opened its environment won’t be poluted with environment variables from the last one.
      • This can cause errors when the external dependencies aren’t quite the same between all the repositories, as some packages might be missing, or be different versions.
      • Additional setup for each configuration necessary. Thankfully, if the template is edited to have the correct EnvFile setup, all copies of it will have it too. Copying an already existing configuration also copies the EnvFile setup.

      Running Files in the Debugger without EnvFile extension¶

      This can be done in two ways:

      Open PyCharm using pycharm.bat which can be found in the build directory (this sets some additional environment variables compared with simply opening PyCharm directly).

      • This is preferred if you only have 1 repository with which PyCharm is used. If you need to use PyCharm on multiple repositories, it is recommended that you use the EnvFile extension.

      To edit the configurations go to Run->Run. and select Edit Configurations . This should open up a sub window. Hit the green + in the top left to create a new configuration and name it. In order to tell PyCharm where to look for python modules and libraries we need to add some folders to the PATH environment variable. Click on the . next to the Environment Variables box, and hit the + icon. In the Name column enter “PATH”, in the value column enter the following;

      The semi-colon delimited list of paths should end in ;%PATH% so that we prepend to the existing list of paths rather than overwriting them.

      You should now be able to run and debug the scripts using the newly created configuration, by adding the full path of the file in the Script path box at the top of the configuration window.

      As an example, create a new file in <Mantid Source Directory>/scripts/ called test.py . Copy into it the Python code below.

      Testing using PyQt¶

      To test that the above instructions have worked, you can simply create a new Python file with the following content (for PyQt5)

      Local Debugging of Unit Tests with PyCharm¶

      This does not require a PyCharm Professional license for debugging, but requires additional setup for running unit tests.

      1. Go to your Run/Debug Configurations.
      2. Open Templates > Python tests > Unittests configuration.
      3. Set the working directory to <Mantid Build Dir>/bin/Debug , for a Debug build, or <Mantid Build Dir>/bin/Release for a Release build.
      4. Add the EnvFile to the Unittests configuration, instructions in Running Files in the Debugger with EnvFile extension .
      5. You should now be able to click the Run/Debug icons next to each unit test method or class to run/debug them.

      Remote Debugging of Unit Tests with PyCharm¶

      This requires a PyCharm Professional license for the Remote Debugging feature.

      This approach can be used to debug unit tests. However, as the required package pydevd is not shipped with Mantid, we need to manually add it at runtime. This can be done by appending a directory that contains the installed pydevd package on the PYTHONPATH . The following code does so at runtime:

      A Remote Debugging configration needs to be setup to use the 44444 port (can be changed, but it needs to be reflected in the code), and running before the tests are run!

      The pydevd package does not have to be installed on Python 2. As of 12/11/2018 installing pydevd on a separate installation with Python 3.7, and adding the code above successfully connects.

      Setting up PyCharm on Linux¶

      Use the native python interpreter ( /usr/bin/python2.7 ) rather than from <Mantid Source Directory>/external/src/ThirdParty/lib/python2.7/python.exe

      In the Project Structure sub menu you should see your root directory with the source/build directories both visible (if not, add them). The folder structure should be present in the centre of the window allowing you to mark folders orange (excluded) or blue (source). Source directories will be searched for python code.

      Within the source directory add the following to your sources:

      If you are writing scripts in any other directories, you can also mark them as sources. This helps PyCharm give better auto-complete and import suggestions during development.

      Additionally, in the Mantid build directory add the following as source folders:

      It is recommended that you add the whole build folder to excluded . This will not interfere with the bin directory, inside the build, being used as a source folder. It will just limit the scope that PyCharm searches for files, classes, etc.

      Go to Run->Run… and select Edit Configurations. Go to Templates > Python. Make <Mantid Build Directory>/bin; the Working Directory . This will then be used for all Python configurations you make.

      Useful Plugins¶

      You can install non-default plugins by pressing Ctrl+Alt+S to open the Settings/Preferences dialog and then going to Plugins. From here you can manage plugins, or add new ones by clicking Browse repositories.

      The following non-default plugins are things our team has found useful for Mantid development:

      • Markdown support — Side by side rendering of markdown documents such as«.md« , .rst (requires Graphviz to show graphs in preview)
      • dotplugin — Syntax highlighting for DOT
      • BashSupport — Syntax highlighting for BASH scripts
      • CMD Support — Syntax highlighting for .BAT

      Add directory to Python path in PyCharm?

      I want to be able to use the paraview.simple library in PyCharm. I already have paraview installed in my computer. This package cannot be installed with pip and there are no .whl files as far as I can tell. The website docs recommend that the directory containing all the python files be added to PYTHONPATH.

      How do I add the relevant folder in PYTHONPATH on my PyCharm session, and keep it there by default, such that when I close out and reopen the paraview.simple library is still available?

      5 Answers 5

      You can add custom paths this way.

      • Go to File->Settings->project Interpreter
      • In the Project-Interpreter field, click the down facing arrow and select «show All»
      • In that Menu, highlight your interpreter and then in the right menu, select the button «Show paths for the selected interpreter» (this is the last button)
      • click the plus symbol to add your path

      Adding interpreter paths in PyCharm:

      1. Project Settings/Project Interpreter: select «settings» icon
      2. Project Interpreters: select «tree» icon
      3. Interpreter Paths: select «plus» icon

      Screenshot

      In PyCharm version 2020.3.1 use the following workflow instead (see official docs):

      Ctrl+Alt+S — open Settings.

      You will see project folder structure. Mark subfolders as Sources or Excluded

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

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