- Pycharm не распознает пакеты проектов
- 2 ответа
- Python in PyCharm. Import from other folder not marking folder as Sources Root
- 1 Answer 1
- Pycharm 5.0.1: сканирование файлов для индексации навсегда
- 5 ответов
- Configuring Project Structure
- Create a content root
- Remove a content root
- Assign a category to a folder in the Project tool window
- Assign a category to a folder in the project settings
- Ошибка PyCharm: «Нет модуля» при попытке импортировать собственный модуль (скрипт Python)
- Приложение 2015-Фев-25
Pycharm не распознает пакеты проектов
Pycharm не распознает пакеты модулей моего проекта.
Я заметил, что по этому вопросу уже есть довольно много вопросов, но я попробовал все приведенные решения, и ничего не работает.
Я пробовал:
— Mark directory as source root и проверка Add sources root to pythonpath
— Открытие другого проекта, а затем повторное открытие исходного, чтобы pycharm переиндексировал пакеты.
2 ответа
Хорошо, довольно забавно отвечать на мой собственный вопрос, но я понял, что это поощряемый путь, если вы действительно нашли ответ.
Так что причиной этой проблемы было то, что __init__.py был указан как текстовый файл в настройках Pycharm.
Если вы перейдете на Settings | File Types | Выбрать Text , вы увидите список имен / расширений файлов, которые Pycharm распознает как текст.
Я думаю, это произошло потому, что я создал файл с именем __init__ без расширения, а затем изменил его на __init__.py
Удаление этого оттуда устранило проблему.
На всякий случай люди попали сюда с такой же проблемой, как и я. У меня были все файлы init .py правильно, но pycharm не распознал эти пакеты должным образом. Наконец, у меня сработал следующий способ: В pycharm -> щелкните правой кнопкой мыши базовую папку вашего кода -> Выберите «Сделать каталог как» -> Выберите «Корень источников». Надеюсь это поможет.
Источник
Python in PyCharm. Import from other folder not marking folder as Sources Root
To import Python modules from other directories I’ve found a way to mark these directories as sources root in PyCharm. It works.
But when I run the script from command line of course command line doesn’t know about sources root in PyCharm so it’s neccessary to do sys.path.append for every folder where import is from.
So there is double work: in Pycharm marking directories as sources root and adding to sys.path to run as script.
Is it any way to avoid the double work? Anything that allows import modules from different directories in Pycharm and command line.
1 Answer 1
Anything that allows import modules from different directories in Pycharm and command line
You are already using virtual environments, right? If you make your code «installable» then, once it is «installed» in your virtual environment, you will be able to import it no matter in which directory you are. This is much better than tweaking «sys.path.append».
To do that you can write the setup.py file (see this link for that) and use distutils package. Another option (easier in my opinion) is to create a pyproject.toml file with poetry.
Going the «poetry route», you install poetry once and then you can just run
This initializes the project structure and creates the «pyproject.toml» file. You can now edit «pyproject.toml» as you wish. You can also add dependencies to your project with
Now when you run poetry install it will create a virtual environment, install the dependencies in it as well as your library. In a shell, you just need to activate the virtual environment (use poetry shell for that) and everything will work. In pycharm, you just need to set your project interpreter to the one in the virtual environment created by poetry (there is also a poetry plugin for pycharm).
Источник
Pycharm 5.0.1: сканирование файлов для индексации навсегда
Я использую PyCharm Community Edition 5.0.1 До вчерашнего дня все работало нормально. Но это застряло в «Сканирование файлов для индексации» в течение очень долгого времени. Со вчерашнего дня.
Я попытался переустановить его, а также попытался сделать недействительным кеш.
Я могу вносить изменения в программы и использовать его как текстовый редактор, но не могу запустить какой-либо файл. Кто-нибудь может помочь? Благодарю.
5 ответов
Исключите папки, которые вы не хотите индексировать. Вы можете сделать это, щелкнув правой кнопкой мыши папку, которую хотите исключить, затем выберите Mark Directory As > Excluded , и PyCharm не будет индексировать эти файлы.
В некоторых случаях это происходит потому, что Pycharm сканирует и индексирует PYTHONPATH. Я понял, что какой-то общий скрипт, который я запускал, был изменен каким-то нинкомпактом (пусть его отрубленная голова скоро украсит наш ров), и каталог / homes попал в PYTHONPATH.
Как это вытащить: Перейдите в Файл-> Настройки-> Проект: [ваш проект] -> Project Interpreter .
С правой стороны вы увидите зубчатое колесо, нажмите его и выберите Показать все . .
В следующем окне ваша среда будет выбрана. В правой части этого окна есть несколько значков, одним из которых является дерево каталогов. Нажмите на это.
Вы найдете список всех путей интерпретатора. Удалите каталог, который вызывает вашу проблему, танцуйте немного танца победы и возобновите работу.
По моему опыту это может быть любая из следующих проблем:
- Вы добавили в свой проект новую папку, которая включает в себя множество файлов. Затем следуйте совету из sP_ и используйте Right click > Mark Directory As > Excluded
- У вас просто была эта проблема в первый раз. Используйте File > Invalidate Cache and Restart
- Это происходит по конкретному проекту. Если вы хотите отказаться от всех настроек проекта, удалите папку .idea проекта. Кончик Игоря Помаранского.
- Если вы работаете над Linux, вы можете проверить этот ответ на аналогичный вопрос.
- Это продолжает происходить. Если вы хотите отказаться от всех своих настроек, удалите папку
Может быть, есть какие-то проблемы в файлах проекта? Попробуйте удалить папку .idea внутри вашего проекта (но это также удалит все настройки проекта).
Постарайтесь убедиться, что в вашем каталоге нет сжатых файлов, поскольку удаление этого может значительно повысить скорость. это сработало для меня!
Источник
Configuring Project Structure
In PyCharm, content is a collection of files with which you are currently working, possibly organized in a hierarchy of subfolders. The top-level folder of a project is its content root .
Within a content root, PyCharm can distinguish between the folders that contain source code, and the ones to be ignored while searching, parsing, watching and so on. To distinguish different types of folders, mark any folder below a content root as a source folder or as excluded.
Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports
Excluded roots contain files and folders ignored by PyCharm when indexing, searching, parsing, watching, and so on.
Test sources roots These folders keep code related to testing separately from production code. Code sources and test sources are normally placed into different folders.
Resource roots (PyCharm Professional only) are intended for resource files in your application (images, Style Sheets, and so on). By assigning a folder to this category, you tell PyCharm that files in it and in its subfolders can be referenced relative to this folder instead of specifying full paths to them.
Namespace package With namespace packages you can create the sub-packages and modules within a single package. You can mark any directory as a namespace package to resolve import statements within that directory.
Template roots (PyCharm Professional only) contain templates for the various web projects.
To access project structure, open Settings/Preferences dialog by pressing Ctrl+Alt+S or by choosing File | Settings for Windows and Linux or PyCharm | Preferences for macOS, then expand the Project node, and select Project Structure .
Create a content root
Open the Project Structure settings.
In the Projects pane of the Project Structure page, click the project you want to configure content roots for.
In the Content roots of the Project Structure page, click the Add Content Root button .
In the dialog that opens, locate the desired directory and click OK .
Remove a content root
Open the Project Structure settings.
In the Projects pane of the Project Structure page, click the project you want to configure content roots for.
In the Content roots pane of the Project Structure page, select the content root that you want to delete.
Click the Remove button and confirm removal.
You can assign a folder to a different category. This can be done both in the Project tool window and on the Project Structure page of the Settings/Preferences dialog.
Assign a category to a folder in the Project tool window
Open the Project tool window (for example View | Tool Windows | Project ).
Select the folder that you want to assign to a certain category.
Right-click it and select the desired category from Mark Directory As menu.
In a similar way you can change the folder category at a later time. (Just select a different category from the context menu.)
To cancel the folder association with its current category (that is to make a folder an «ordinary» folder
Assign a category to a folder in the project settings
Open Project Structure page of the Settings/Preferences dialog ( Ctrl+Alt+S ).
Select the folder you want to assign a category to.
Click the category button, for example,
You can make files and folders excluded by specifying the name patterns. Use the Exclude files field to specify the patterns.
The files and folders whose names match at least one of the specified patterns are made excluded. Folders are excluded along with all their contents.
Источник
Ошибка PyCharm: «Нет модуля» при попытке импортировать собственный модуль (скрипт Python)
Я написал модуль (файл my_mod.py файл находится в папке my_module ). В настоящее время я работаю в файле, cool_script.py который находится в папке cur_proj . Я открыл папку в PyCharm, используя File — open (и я предполагаю, следовательно, это проект PyCharm).
В ProjectView (CMD-7) я вижу свой проект cur_proj (красным) и в разделе «Внешние библиотеки» my_module . В cool_script.py я могу написать
и PyCharm даже делает предложение для my_mod. Все идет нормально.
Тем не менее, когда я пытаюсь запустить cool_script.py, PyCharm сообщает мне «Нет модуля с именем my_module»
Это кажется странным для меня, потому что
А) в терминале (OS 10.10.2), в python, я могу импортировать модуль без проблем — в PYTHONPATH есть соответствующая запись в .bashrc
B) в PyCharm — Настройки — Project cur_proj — Project Interpreter — CogWheel рядом с интерпретатором python — подробнее — показать пути для иконки выбранного переводчика, пути из PYTHONPATH действительно появляются (как я думаю, они должны)
Следовательно, почему я получаю сообщение об ошибке при попытке запустить cool_script.py? — Чего мне не хватает?
Приложение 2015-Фев-25
Когда я захожу в PyCharm для запуска — Редактировать конфигурации, для моего текущего проекта есть две опции, которые выбираются с галочкой: « Добавить корни содержимого в PYTHONPATH » и « Добавить корни источника в PYTHONPATH ». Когда я снял оба флажка, я могу загрузить свой модуль.
Так что это работает сейчас — но почему ?
Возникли дополнительные вопросы:
- Что такое «корни контента» и что такое «корни источников»? И почему добавление чего-либо к PYTHONPATH делает его каким-то образом ломающимся?
- я должен снять все эти опции все время (также и в настройках по умолчанию, а не только в конкретных конфигурациях проекта (левая панель диалога Run / Debug Configurations)?
Источник