PyLint“가져올 수 없습니다”오류-PYTHONPATH를 설정하는 방법?
Windows의 Wing IDE 내에서 PyLint를 실행하고 있습니다. 프로젝트에 하위 디렉토리 (패키지)가 있고 패키지 내부에 최상위 레벨에서 모듈을 가져옵니다.
__init__.py
myapp.py
one.py
subdir\
__init__.py
two.py
내부 two.py
에는 import one
최상위 디렉토리 ( myapp.py
실행 디렉토리 )가 Python 경로에 있기 때문에 런타임에 올바르게 작동합니다 . 그러나 two.py에서 PyLint를 실행하면 오류가 발생합니다.
F0401: Unable to import 'one'
이 문제를 어떻게 해결합니까?
내가 알고있는 두 가지 옵션이 있습니다.
하나, PYTHONPATH
모듈 위에 디렉토리를 포함 하도록 환경 변수를 변경하십시오 .
또는 ~/.pylintrc
다음과 같이 모듈 위에 디렉토리를 포함하도록 편집 하십시오.
[MASTER]
init-hook='import sys; sys.path.append("/path/to/root")'
(또는 다른 버전의 pylint에서 init-hook은 [General]을 [MASTER]로 변경해야합니다)
이 두 옵션 모두 작동해야합니다.
희망이 도움이됩니다.
1) sys.path는 목록입니다.
2) 문제는 때때로 sys.path가 virtualenv.path가 아니며 virtualenv 에서 pylint를 사용하려는 경우입니다
3) 따라서, init-hook을 사용하십시오 ( '및 "pylint 구문 분석은 엄격합니다)
[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'
또는
[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'
.. 및
pylint --rcfile /path/to/pylintrc /path/to/module.py
경로를 변경하는 솔루션 init-hook
은 좋지만 절대 경로를 추가해야한다는 사실을 싫어합니다. 결과적 으로이 pylintrc 파일을 프로젝트 개발자와 공유 할 수 없습니다. pylintrc 파일의 상대 경로를 사용하는이 솔루션은 나에게 더 효과적입니다.
[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"
참고 pylint.config.PYLINTRC
또한 존재하고 같은 값을 가진다 find_pylintrc()
.
__init__.py
파이썬에게 dirs가 모듈이라는 것을 알리기 위해 두 디렉토리에 빈 파일이 있습니까?
폴더 내에서 실행하지 않을 때의 기본 개요는 (예를 들어 사용하지 않았지만 pylint 's에서) 다음과 같습니다.
topdir\
__init__.py
functions_etc.py
subdir\
__init__.py
other_functions.py
이 그렇다면 pylint가 자신의 절대 경로에서 실행되고있는 현재 디렉토리를 참조하지 않고 모듈의 인식 통역 파이썬, 그것은 액세스 할 수 있습니다 방법입니다 functions_etc.py
같은 topdir.functions_etc
또는 topdir.subdir.other_functions
제공, topdir
온입니다 PYTHONPATH
.
업데이트 : 문제가 __init__.py
파일 이 아닌 경우 모듈을 복사하거나 이동하십시오. c:\Python26\Lib\site-packages
추가 패키지를 넣는 일반적인 장소이며 pythonpath에 있습니다. Windows 심볼릭 링크 또는 이와 동등한 기능을 수행하는 방법을 알고 있다면 대신 할 수 있습니다. http://docs.python.org/install/index.html 에는 개발 코드의 사용자 수준 디렉토리에 sys.path를 추가하는 옵션을 포함하여 더 많은 옵션이 있지만 실제로는 일반적으로 심볼릭 링크입니다. 내 로컬 개발 디렉토리를 사이트 패키지에 복사하는 것이 동일한 효과입니다.
venv에서 pylint 경로를 구성하면 문제를 해결할 수 있습니다. $ cat .vscode / settings.json
{
"python.pythonPath": "venv/bin/python",
"python.linting.pylintPath": "venv/bin/pylint"
}
WingIDE와 어떻게 작동하는지 모르겠지만 Geany와 함께 PyLint를 사용하려면 외부 명령을 다음과 같이 설정하십시오.
PYTHONPATH=${PYTHONPATH}:$(dirname %d) pylint --output-format=parseable --reports=n "%f"
where %f is the filename, and %d is the path. Might be useful for someone :)
I had to update the system PYTHONPATH
variable to add my App Engine path. In my case I just had to edit my ~/.bashrc
file and add the following line:
export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder
In fact, I tried setting the init-hook
first but this did not resolve the issue consistently across my code base (not sure why). Once I added it to the system path (probably a good idea in general) my issues went away.
One workaround that I only just discovered is to actually just run PyLint for the entire package, rather than a single file. Somehow, it manages to find imported module then.
Try
if __name__ == '__main__':
from [whatever the name of your package is] import one
else:
import one
Note that in Python 3, the syntax for the part in the else
clause would be
from .. import one
On second thought, this probably won't fix your specific problem. I misunderstood the question and thought that two.py was being run as the main module, but that is not the case. And considering the differences in the way Python 2.6 (without importing absolute_import
from __future__
) and Python 3.x handle imports, you wouldn't need to do this for Python 2.6 anyway, I don't think.
Still, if you do eventually switch to Python 3 and plan on using a module as both a package module and as a standalone script inside the package, it may be a good idea to keep something like
if __name__ == '__main__':
from [whatever the name of your package is] import one # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
from .. import one
in mind.
EDIT: And now for a possible solution to your actual problem. Either run PyLint from the directory containing your one
module (via the command line, perhaps), or put the following code somewhere when running PyLint:
import os
olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)
Basically, as an alternative to fiddling with PYTHONPATH, just make sure the current working directory is the directory containing one.py
when you do the import.
(Looking at Brian's answer, you could probably assign the previous code to init_hook
, but if you're going to do that then you could simply do the appending to sys.path
that he does, which is slightly more elegant than my solution.)
The key is to add your project directory to sys.path
without considering about the env variable.
For someone who use VSCode, here's a one-line solution for you if there's a base directory of your project:
[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+\/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'
Let me explain it a little bit:
re.search(r".+\/" + base_dir, os.getcwd()).group()
: find base directory according to the editing fileos.path.join(os.getcwd(), base_dir)
: addcwd
tosys.path
to meet command line environment
FYI, here's my .pylintrc:
https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f
I had this same issue and fixed it by installing pylint in my virtualenv and then adding a .pylintrc file to my project directory with the following in the file:
[Master]
init-hook='sys.path = list(); sys.path.append("./Lib/site-packages/")'
Maybe by manually appending the dir inside the PYTHONPATH?
sys.path.append(dirname)
I had the same problem and since i could not find a answer I hope this can help anyone with a similar problem.
I use flymake with epylint. Basically what i did was add a dired-mode-hook that check if the dired directory is a python package directory. If it is I add it to the PYTHONPATH. In my case I consider a directory to be a python package if it contains a file named "setup.py".
;;;;;;;;;;;;;;;;;
;; PYTHON PATH ;;
;;;;;;;;;;;;;;;;;
(defun python-expand-path ()
"Append a directory to the PYTHONPATH."
(interactive
(let ((string (read-directory-name
"Python package directory: "
nil
'my-history)))
(setenv "PYTHONPATH" (concat (expand-file-name string)
(getenv ":PYTHONPATH"))))))
(defun pythonpath-dired-mode-hook ()
(let ((setup_py (concat default-directory "setup.py"))
(directory (expand-file-name default-directory)))
;; (if (file-exists-p setup_py)
(if (is-python-package-directory directory)
(let ((pythonpath (concat (getenv "PYTHONPATH") ":"
(expand-file-name directory))))
(setenv "PYTHONPATH" pythonpath)
(message (concat "PYTHONPATH=" (getenv "PYTHONPATH")))))))
(defun is-python-package-directory (directory)
(let ((setup_py (concat directory "setup.py")))
(file-exists-p setup_py)))
(add-hook 'dired-mode-hook 'pythonpath-dired-mode-hook)
Hope this helps.
In case anybody is looking for a way to run pylint as an external tool in PyCharm and have it work with their virtual environments (why I came to this question), here's how I solved it:
- In PyCharm > Preferences > Tools > External Tools, Add or Edit an item for pylint.
- In the Tool Settings of the Edit Tool dialog, set Program to use pylint from the python interpreter directory:
$PyInterpreterDirectory$/pylint
- Set your other parameters in the Parameters field, like:
--rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$
- Set your working directory to
$FileDir$
Now using pylint as an external tool will run pylint on whatever directory you have selected using a common config file and use whatever interpreter is configured for your project (which presumably is your virtualenv interpreter).
I found a nice answer from https://sam.hooke.me/note/2019/01/call-python-script-from-pylint-init-hook/ edit your pylintrc and add the following in master init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"
if you using vscode,make sure your package directory is out of the _pychache__ directory.
This is an old question but has no accepted answer, so I'll suggest this: change the import statement in two.py to read:
from .. import one
In my current environment (Python 3.6, VSCode using pylint 2.3.1) this clears the flagged statement.
If you are using Cython in Linux, I resolved removing module.cpython-XXm-X-linux-gnu.so
files in my project target directory.
Hello i was able to import the packages from different directory. I just did the following: Note: I am using VScode
Steps to Create a Python Package Working with Python packages is really simple. All you need to do is:
Create a directory and give it your package's name. Put your classes in it. Create a init.py file in the directory
For example: you have a folder called Framework where you are keeping all the custom classes there and your job is to just create a init.py file inside the folder named Framework.
And while importing you need to import in this fashion--->
from Framework import base
so the E0401 error disappears Framework is the folder where you just created init.py and base is your custom module which you are required to import into and work upon Hope it helps!!!!
참고URL : https://stackoverflow.com/questions/1899436/pylint-unable-to-import-error-how-to-set-pythonpath
'IT story' 카테고리의 다른 글
Git에서 이전 커밋 메시지 변경 (0) | 2020.07.09 |
---|---|
목록을 전송하는 가장 효율적인 방법 (0) | 2020.07.09 |
VS2010 웹 배포 패키지를 사용하여 추가 파일을 어떻게 포함합니까? (0) | 2020.07.09 |
Devise로 이메일 확인을 어떻게 설정합니까? (0) | 2020.07.09 |
문자열을 템플릿 문자열로 변환 (0) | 2020.07.09 |