Python을 다른 폴더에서 가져올 수 없습니다.
Python이 하위 폴더의 모듈을 가져 오도록 할 수없는 것 같습니다. 가져온 모듈에서 클래스의 인스턴스를 만들려고 할 때 오류가 발생하지만 가져 오기 자체는 성공합니다. 다음은 내 디렉토리 구조입니다.
Server
-server.py
-Models
--user.py
다음은 server.py의 내용입니다.
from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
그리고 user.py :
class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
오류 : AttributeError : '모듈'개체에 '사용자'속성이 없습니다.
__init__.py
Python이 모듈로 취급하도록 Models 디렉토리에 파일을 만들어야한다고 생각합니다 .
그런 다음 다음을 수행 할 수 있습니다.
from Models.user import User
에 코드를 포함하거나 __init__.py
(예 : 몇 가지 다른 클래스에 필요한 초기화 코드) 비워 둘 수 있습니다. 하지만 거기에 있어야합니다.
하위 폴더 에 만들어야 __init__.py
합니다 Models
. 파일이 비어있을 수 있습니다. 패키지를 정의합니다.
그런 다음 다음을 수행 할 수 있습니다.
from Models.user import User
여기에 있는 파이썬 튜토리얼에서 모든 것을 읽으 십시오 .
여기 에 파이썬 프로젝트의 파일 구성에 대한 좋은 기사도 있습니다 .
사용자 가져 오기
u = user.User () #이 줄의 오류
위에서 언급 한 __init__가 없기 때문에 문제를 더 명확하게 만드는 ImportError가 예상됩니다.
'user'도 표준 라이브러리의 기존 모듈이기 때문에 얻을 수 없습니다. import 문은 그 문을 잡고 그 안에서 User 클래스를 찾으려고합니다. 존재하지 않는 경우에만 오류가 발생합니다.
일반적으로 가져 오기를 절대적으로 만드는 것이 좋습니다.
import Server.Models.user
이런 종류의 모호함을 피하기 위해. 실제로 Python 2.7에서 '사용자 가져 오기'는 현재 모듈에 대해 전혀 상대적으로 보이지 않습니다.
상대 가져 오기를 정말로 원한다면 다소 추한 구문을 사용하여 Python 2.5 이상에서 명시 적으로 가져올 수 있습니다.
from .user import User
표준 패키지 구조가없는 경우 상위 폴더에있는 모듈을 가져 오는 올바른 방법은 다음과 같습니다.
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
(마지막 두 줄을 병합 할 수 있지만이 방법이 이해하기 더 쉽습니다).
이 솔루션은 크로스 플랫폼이며 다른 상황에서 수정할 필요가 없을 정도로 일반적입니다.
__init__.py가 누락되었습니다. Python 자습서에서 :
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
Put an empty file named __init__.py in your Models directory, and all should be golden.
how do you write out the parameters os.path.dirname
.... command?
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
My preferred way is to have __init__.py on every directory that contains modules that get used by other modules, and in the entry point, override sys.path as below:
def get_path(ss):
return os.path.join(os.path.dirname(__file__), ss)
sys.path += [
get_path('Server'),
get_path('Models')
]
This makes the files in specified directories visible for import, and I can import user from Server.py.
After going through the answers given by these contributors above - Zorglub29, Tom, Mark, Aaron McMillin, lucasamaral, JoeyZhao, Kjeld Flarup, Procyclinsur, martin.zaenker, tooty44 and debugging the issue that I was facing I found out a different use case due to which I was facing this issue. Hence adding my observations below for anybody's reference.
In my code I had a cyclic import of classes. For example:
src
|-- utilities.py (has Utilities class that uses Event class)
|-- consume_utilities.py (has Event class that uses Utilities class)
|-- tests
|-- test_consume_utilities.py (executes test cases that involves Event class)
I got following error when I tried to execute python -m pytest tests/test_utilities.py for executing UTs written in test_utilities.py.
ImportError while importing test module '/Users/.../src/tests/test_utilities.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_utilities.py:1: in <module>
from utilities import Utilities
...
...
E ImportError: cannot import name 'Utilities'
The way I resolved the error was by re-factoring my code to move the functionality in cyclic import class so that I could remove the cyclic import of classes.
Note, I have __init__.py
file in my 'src' folder as well as 'tests' folder and still was able to get rid of the 'ImportError' just by re-factoring the code.
Following stackoverflow link provides much more details on Circular dependency in Python.
참고URL : https://stackoverflow.com/questions/456481/cant-get-python-to-import-from-a-different-folder
'code' 카테고리의 다른 글
sed를 사용하여 문자열에서 텍스트를 추출하는 방법은 무엇입니까? (0) | 2020.09.24 |
---|---|
MiniTest의 assert_raises / must_raise에서 예외 메시지를 확인하기위한 예상 구문은 무엇입니까? (0) | 2020.09.24 |
성능 및 Java 상호 운용성 : Clojure 대 Scala (0) | 2020.09.24 |
자바 : 클래스의 모든 변수 이름 가져 오기 (0) | 2020.09.24 |
"선택기 배열"을 만드는 방법 (0) | 2020.09.24 |