PyCharm 오류 : 자체 모듈을 가져 오려고 할 때 '모듈 없음'(파이썬 스크립트)
모듈 ( my_mod.py
폴더에 있는 파일 파일 my_module
)을 작성했습니다. 현재 cool_script.py
폴더 에있는 파일에서 작업 하고 있습니다 cur_proj
. File-open을 사용하여 PyCharm에서 폴더를 열었습니다 (따라서 PyCharm 프로젝트라고 가정합니다).
ProjectView (CMD-7)에서 내 프로젝트 cur_proj
(빨간색)를 볼 수 있고 "외부 라이브러리"아래에 표시 my_module
됩니다. cool_script.py에서 쓸 수 있습니다
from my_module import my_mod as mm
PyCharm도 my_mod를 제안합니다. 여태까지는 그런대로 잘됐다.
그러나 cool_script.py를 실행하려고하면 PyCharm에서 "my_module이라는 모듈이 없습니다"라고 말합니다.
나에게는 이상해 보인다. 왜냐하면
A) 터미널 (OS 10.10.2)의 파이썬에서는 모듈을 아무런 문제없이 가져올 수 있습니다-.bashrc의 PYTHONPATH에 해당하는 항목이 있습니다
B) PyCharm-설정-프로젝트 cur_proj-프로젝트 인터프리터-Python 인터프리터 옆에 CogWheel-자세히-선택한 인터프리터 아이콘의 경로를 표시하면 PYTHONPATH의 경로가 나타납니다 (필자가 생각하는 것처럼)
따라서 cool_script.py를 실행하려고하면 왜 오류가 발생합니까? - 내가 무엇을 놓치고 있습니까?
노트:
- 나는 다른 / 특별 파이썬 버전을 선언하지 cool_script.py의 상단에
- 경로 가 올바른지 확인했습니다 .
my_module
- 내가 넣어
__init__.py
파일 (빈 파일) 모두my_module
와의를cur_proj
- 사용하지 않습니다
virtualenv
부록 2015 년 2 월 25 일
PyCharm에서 Run to Configuration-Edit Configurations로 이동하면 " PYTHONPATH에 컨텐츠 루트 추가 "및 " PYTHONPATH에 소스 루트 추가 " 확인 표시가있는 두 가지 옵션이 있습니다 . 둘 다 체크하지 않으면 모듈을로드 할 수 있습니다.
이제 작동 하지만 왜 그렇 습니까?
추가 질문이 생겼습니다.
- "컨텐츠 루트"란 무엇이며 "소스 루트"는 무엇입니까? 그리고 왜 PYTHONPATH에 무언가를 추가하면 어떻게 든 파괴됩니까?
- 항상 두 옵션을 모두 선택 해제해야합니까 (따라서 기본값은 프로젝트 특정 구성뿐만 아니라 실행 / 디버그 구성 대화 상자의 왼쪽 패널)?
자신의 모듈이 동일한 경로에있는 경우 경로를로 표시해야합니다 Sources Root
. 프로젝트 탐색기에서 가져 오려는 디렉토리를 마우스 오른쪽 단추로 클릭하십시오. 그런 다음를 선택 Mark Directory As
하고 선택하십시오 Sources Root
.
이게 도움이 되길 바란다.
PyCharm 커뮤니티 / 전문가 2018.2.1
나는 지금이 문제를 겪고 있었고 @Beatriz Fonseca와 @Julie가 지적한 것과 비슷한 방식으로 해결할 수있었습니다.
당신이로 이동합니다 File
> - Settings
-> Project: YourProjectName
-> Project Structure
., 당신은 당신이 현재에서 작업하는 프로젝트의 디렉토리 레이아웃을해야합니다 당신은 당신의 디렉토리를 이동하고 중 하나 인로 레이블을해야합니다 Source
모든 소스 파일에 대한 디렉토리 또는 Resource
가져 오기 전용 파일 의 폴더로 사용할 수 있습니다.
또한 __init__.py
리소스 디렉토리 내에 파일을 가져 오거나 실제로 가져 오려는 위치에 파일 을 배치 하면 완벽하게 작동합니다.
이 답변이 누군가를 돕기를 희망하며 JetBrains 가이 성가신 버그를 해결하기를 바랍니다.
그래서 가면
-> 설정-> 프로젝트 : My_project-> 프로젝트 구조,
소스 코드를 사용할 수있는 디렉토리 만 "소스"로 표시하십시오 (u는 동일한 창에서 볼 수 있음). 소스 코드가있는 디렉토리는 파란색으로 바뀌어야합니다. 이제 같은 디렉토리에있는 모듈에서 가져올 수 있습니다.
내가 시도한 것은 내 파일이있는 위치를 찾는 것입니다.
예 : E:\git_projects\My_project\__init__.py is my location.
파일-> 설정-> 프로젝트 : My_project-> 프로젝트 구조로 이동하여 언급 장소에 대한 내용 루트를 추가했습니다. E:\git_projects\My_project
그것은 나를 위해 일했다.
my_module
is a folder not a module and you can't import a folder, try moving my_mod.py
to the same folder as the cool_script.py
and then doimport my_mod as mm
. This is because python only looks in the current directory and sys.path
, and so wont find my_mod.py
unless it's in the same directory
Or you can look here for an answer telling you how to import from other directories.
As to your other questions, I do not know as I do not use PyCharm.
This can be caused when Python interpreter can't find your code. You have to mention explicitly to Python to find your code in this location.
To do so:
- Go to your python console
- Add
sys.path.extend(['your module location'])
to Python console.
In your case:
- Go to your python console,
On the start, write the following code:
import sys sys.path.extend([my module URI location])
Once you have written this statement you can run following command:
from mymodule import functions
The key confusing step that must be done is to recreate the run configuration for the source file that you're trying to execute, so that the IDE picks up the new paths.
The way that actually worked for me was to go to Run/Edit Configurations..., select the configuration for the file that you're trying to run on the left side, uncheck the "Add source roots to PYTHONPATH" box, save, and then go back and check the box and save. THEN it would work.
I was getting the error with "Add source roots to PYTHONPATH" as well. My problem was that I had two folders with the same name, like project/subproject1/thing/src
and project/subproject2/thing/src
and I had both of them marked as source root. When I renamed one of the "thing"
folders to "thing1"
(any unique name), it worked.
Maybe if PyCharm automatically adds selected source roots, it doesn't use the full path and hence mixes up folders with the same name.
Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.
Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.
Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.
Pycharm 2017.1.1
- Click on
View->ToolBar
&View->Tool Buttons
- On the left pane
Project
would be visible, right click on it and pressAutoscroll to source
and then run your code.
This worked for me.
The solution for this problem without having to Mark Directory as Source Root is to Edit Run Configurations and in Execution select the option "Redirect input from" and choose script you want to run. This works because it is then treated as if the script was run interactively in this directory. However Python will still mark the module name with an error "no module named x":
When the interpreter executes the import statement, it searches for x.py in a list of directories assembled from the following sources:
- The directory from which the input script was run or the current directory if the interpreter is being run interactively
- The list of directories contained in the PYTHONPATH environment variable, if it is set.
- An installation-dependent list of directories configured at the time Python is installed, in my case usr/lib/python3.6 on Ubuntu.
ln -s . someProject
If you have someDirectory/someProjectDir and two files, file1.py and file2.py, and file1.py tries to import with this line
from someProjectDir import file2
It won't work, even if you have designated the someProjectDir as a source directory, and even if it shows in preferences, project, project structure menu as a content root. The only way it will work is by linking the project as show above (unix command, works in mac, not sure of use or syntax for Windows). There seems some mechanism where Pycharm does this automatically either in checkout from version control or adding as context root, since the soft link was created by Pycharm in a dependent project. Hence, just copying the same, although the weird replication of directory is annoying and necessity is perplexing. Also in the dependency where auto created, it doesn't show as new directory under version control. Perhaps comparison of .idea files will reveal more.
The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:
- "Add content roots to PYTHONPATH"
- "Add source roots to PYTHONPATH"
I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.
I received this error when working directory was not set properly. It was very odd, since it was a fresh installation, and I can't think of a reason why PyCharm would use some random directory as a working directory for the project, instead of the root dir
'development' 카테고리의 다른 글
자유 거리 / 우편 주소를 텍스트 및 구성 요소로 구문 분석하는 방법 (0) | 2020.07.14 |
---|---|
Flags Enum의 값을 반복합니까? (0) | 2020.07.14 |
여러 패턴의 문자형 벡터를 사용하여 grep (0) | 2020.07.14 |
파이썬에서 int를 ASCII로 변환하고 다시 변환하십시오. (0) | 2020.07.14 |
소프트 키보드가 레이아웃을 올리는 것을 피하는 방법은 무엇입니까? (0) | 2020.07.14 |