Programming

Python 스크립트를 실행하려고 할 때“ImportError : No module named”

procodes 2020. 8. 3. 21:05
반응형

Python 스크립트를 실행하려고 할 때“ImportError : No module named”


파이썬 스크립트를 시작하는 스크립트를 실행하려고합니다. ImportError : No module named ...라는 메시지가 표시되지만 ipython을 시작하고 인터프리터를 통해 동일한 방식으로 동일한 모듈을 가져 오면 모듈이 허용됩니다.

무슨 일이 일어나고 어떻게 해결할 수 있습니까? 파이썬이 PYTHONPATH를 어떻게 사용하는지 이해하려고 노력했지만 완전히 혼란 스럽습니다. 어떤 도움이라도 대단히 감사하겠습니다.


이 문제는 명령 행 IPython 인터프리터가 현재 경로를 사용하는 방법과 별도의 프로세스 (IPython 노트북, 외부 프로세스 등) 와 같은 방식으로 인해 발생합니다 . IPython은 sys.path뿐만 아니라 현재 작업중인 디렉토리에서도 가져올 모듈을 찾습니다. 명령 행에서 인터프리터를 시작할 때 현재 작동중인 디렉토리는 ipython을 시작한 디렉토리와 동일합니다.

import os
os.getcwd() 

이것이 사실임을 알 수 있습니다.

그러나 ipython 노트북을 사용하고 있고 실행 os.getcwd()중이고 현재 작업 디렉토리가 ipython_notebook_config.py 파일에서 노트북이 작동하도록 지시 한 폴더입니다 (일반적으로 c.NotebookManager.notebook_dir설정 사용).

해결책은 파이썬 인터프리터에게 모듈 경로를 제공하는 것입니다. 가장 간단한 해결책은 해당 경로를 sys.path 목록에 추가하는 것입니다. 노트북에서 먼저 다음을 시도하십시오.

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

그래도 문제가 해결되지 않으면 가져 오기 경로와 관련이없는 다른 문제가있는 것이므로 문제에 대한 자세한 정보를 제공해야합니다.

이것을 해결하는 더 나은 (그리고 더 영구적 인) 방법은 PYTHONPATH 를 설정하는 것입니다 . 이것은 PYTHONPATH 를 설정하여 인터프리터에게 파이썬 패키지 / 모듈에 대한 추가 디렉토리를 제공합니다. PYTHONPATH를 전역 변수로 편집하거나 설정하는 것은 운영 체제에 따라 다르며 여기에서 Unix 또는 Windows에 대해 자세히 설명합니다 .


__init__.pypython 프로젝트를 실행하는 동안 폴더 아래 에 이름 으로 빈 python 파일을 작성하면 오류가 표시됩니다.


둘 다 동일한 통역사를 사용하고 있는지 확인하십시오. 우분투에서 나에게 일어난 일 :

$ ipython3 -c 'import sys; print(sys.version)'
3.4.2 (default, Jun 19 2015, 11:34:49) \n[GCC 4.9.1]

$ python3 -c 'import sys; print(sys.version)'
3.3.0 (default, Nov 27 2012, 12:11:06) \n[GCC 4.6.3]

그리고 sys.path두 통역사가 달랐습니다. 이 문제를 해결하기 위해 Python 3.3을 제거했습니다.


이렇게 sys.path.append('my-path-to-module-folder')작동하지만 IPython에 모듈을 사용할 때마다이 작업을 수행하는 것을 방지하기 위해, 당신은 추가 할 수 있습니다 export PYTHONPATH="my-path-to-module-folder:$PYTHONPATH"당신에 ~/.bash_profile파일.


주요 이유는 Python과 IPython의 sys.path가 다르기 때문입니다.

lucypark link를 참조하십시오 . 솔루션이 작동합니다. opencv를 설치하면 발생합니다.

conda install opencv

iPython에서 가져 오기 오류가 발생했습니다.이 문제를 해결하려면 다음 세 단계가 있습니다.

import cv2
ImportError: ...

1. 다음 명령으로 Python 및 iPython의 경로를 확인하십시오.

import sys
sys.path

Python과 Jupyter와는 다른 결과가 나타납니다. 두 번째 단계 sys.path.append는 시도하여 오류로 누락 된 경로를 수정하는 데 사용 하십시오.

2. 임시 솔루션

iPython에서 :

import sys
sys.path.append('/home/osboxes/miniconda2/lib/python2.7/site-packages')
import cv2

ImportError:..문제 해결

3. 영구적 인 해결책

iPython 프로파일을 작성하고 초기 추가를 설정하십시오.

bash 쉘에서 :

ipython profile create
... CHECK the path prompted , and edit the prompted config file like my case
vi /home/osboxes/.ipython/profile_default/ipython_kernel_config.py

vi에서 파일에 추가하십시오.

c.InteractiveShellApp.exec_lines = [
 'import sys; sys.path.append("/home/osboxes/miniconda2/lib/python2.7/site-packages")'
]

끝난


ipython을 설치하기 전에 easy_install을 통해 모듈을 설치했습니다. 말한다 sudo easy_install mechanize.

ipython을 설치 한 후, ipython이 모듈을 인식하도록 easy_install을 다시 실행해야했습니다.


커맨드 라인에서 실행하면 파이썬 인터프리터가 모듈을 찾을 경로를 알지 못하는 경우가 있습니다.

아래는 내 프로젝트의 디렉토리 구조입니다.

/project/apps/..
/project/tests/..

아래 명령을 실행 중이었습니다.

>> cd project

>> python tests/my_test.py

위의 명령을 실행 한 후 오류가 발생했습니다.

no module named lib

lib는 my_test.py에서 가져 왔습니다.

sys.path를 인쇄하고 작업중 인 프로젝트 경로를 sys.path 목록에서 사용할 수 없다는 것을 알았습니다.

스크립트 시작시 아래 코드를 추가했습니다 my_test.py.

import sys
import os

module_path = os.path.abspath(os.getcwd())    

if module_path not in sys.path:       

    sys.path.append(module_path)

I am not sure if it is a good way of solving it but yeah it did work for me.


Had a similar problem, fixed it by calling python3 instead of python, my modules were in Python3.5.


I have found that the solution to this problem was extensively documented here:

https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/

Basically, you must install the packages within the Jupyter environment, issuing shell commands like:

!{sys.executable} -m pip install numpy

Please check the above link for an authoritative full answer.


This is how I fixed it:

import os
import sys
module_path = os.path.abspath(os.getcwd() + '\\..')
if module_path not in sys.path:
    sys.path.append(module_path)

I found yet another source of this discrepancy:

I have ipython installed both locally and in commonly in virtualenvs. My problem was that, inside a newly made virtualenv with ipython, the system ipython was picked up, which was a different version than the python and ipython in the virtualenv (a 2.7.x vs. a 3.5.x), and hilarity ensued.

I think the smart thing to do whenever installing something that will have a binary in yourvirtualenv/bin is to immediately run rehash or similar for whatever shell you are using so that the correct python/ipython gets picked up. (Gotta check if there are suitable pip post-install hooks...)


Solution without scripting:

  1. Open Spyder -> Tools -> PYTHONPATH manager
  2. Add Python paths by clicking "Add Path". E.g: 'C:\Users\User\AppData\Local\Programs\Python\Python37\Lib\site-packages'
  3. Click "Synchronize..." to allow other programs (e.g. Jupyter Notebook) use the pythonpaths set in step 2.
  4. Restart Jupyter if it is open

This is probably caused by different python versions installed on your system, i.e. python2 or python3.

Run command $ pip --version and $ pip3 --version to check which pip is from at Python 3x. E.g. you should see version information like below:

pip 19.0.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

Then run the example.py script with below command

$ python3 example.py

Happened to me with the directory utils. I was trying to import this directory as:

from utils import somefile

utils is already a package in python. Just change your directory name to something different and it should work just fine.


This kind of errors occurs most probably due to python version conflicts. For example, if your application runs only on python 3 and you got python 2 as well, then it's better to specify which version to use. For example use

python3 .....

instead of

python

remove pathlib and reinstall it.

Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command.

pip install pathlib

참고URL : https://stackoverflow.com/questions/15514593/importerror-no-module-named-when-trying-to-run-python-script

반응형