Vì python kiểm tra trong các thư mục theo thứ tự tuần tự bắt đầu từ thư mục đầu tiên trong danh sách sys.path
, cho đến khi tìm thấy tệp .py
mà nó đang tìm kiếm.
Lý tưởng nhất, thư mục hiện tại hoặc thư mục của tập lệnh luôn là phần tử đầu tiên trong danh sách, trừ khi bạn sửa đổi nó, như bạn đã làm. Từ documentation -
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
Vì vậy, có lẽ hầu hết, bạn đã có một tập tin .py
với tên giống như các module bạn đã cố gắng nhập từ, trong thư mục hiện (trong đó kịch bản đã được điều hành từ).
Ngoài ra, một điều cần lưu ý về ImportError
s, cho phép nói những lỗi nhập khẩu nói - ImportError: No module named main
- nó không có nghĩa là main.py
được ghi đè, không có nếu điều đó được ghi đè chúng tôi sẽ không có vấn đề cố gắng để đọc nó. Một số mô-đun của nó ở trên này đã được ghi đè bằng a. py
hoặc một số tệp khác.
Ví dụ -
cấu trúc thư mục của tôi trông như thế nào -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
Bây giờ Từ testmain.py
, tôi gọi from shared import phtest
, nó hoạt động tốt.
Bây giờ cho phép nói rằng tôi giới thiệu một shared.py trong test
directory`, ví dụ -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
Bây giờ khi tôi cố gắng làm from shared import phtest
từ testmain.py
, tôi sẽ nhận được lỗi -
ImportError: cannot import name 'phtest'
Như bạn có thể thấy ở trên, tệp gây ra sự cố là shared.py
, không phải là phtest.py
.
Bản sao có thể có của [Tại sao sử dụng sys.path.append (đường dẫn) thay vì sys.path.insert (1, đường dẫn)?] (Http://stackoverflow.com/questions/10095037/why-use-sys- Module-appendpath-thay-của-sys-path-insert1-path) – CrandellWS