Hướng dẫn python import from another directory init - nhập python từ init thư mục khác

Trong Python 3.4 trở lên, bạn có thể nhập trực tiếp từ tệp nguồn [liên kết đến tài liệu]. Đây không phải là giải pháp đơn giản nhất, nhưng tôi bao gồm câu trả lời này cho sự hoàn chỉnh.

Đây là một ví dụ. Đầu tiên, tệp được nhập, được đặt tên là

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
1:

def announce[]:
    print["Imported!"]

Mã nhập tệp ở trên, được truyền cảm hứng rất nhiều bởi ví dụ trong tài liệu:

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]

Đầu ra:


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Lưu ý rằng tên biến, tên mô -đun và tên tệp không cần phải khớp. Mã này vẫn hoạt động:

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

baz = module_from_file["bar", "/path/to/foo.py"]

if __name__ == "__main__":
    print[baz]
    print[dir[baz]]
    baz.announce[]

Đầu ra:


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!

Lưu ý rằng tên biến, tên mô -đun và tên tệp không cần phải khớp. Mã này vẫn hoạt động:

Cách pythonic nhất để nhập một mô -đun từ một thư mục khác là đặt một tệp trống có tên

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
2 vào thư mục đó và sử dụng đường dẫn tương đối với ký hiệu dấu chấm.import a module from another folder is to place an empty file named
import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
2 into that folder and use the relative path with the dot notation.

Ví dụ: một mô -đun trong thư mục chính sẽ được nhập bằng

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
3. Tệp
import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
2 báo hiệu cho Python rằng thư mục nên được coi là gói.package.

Xây dựng vấn đề

Vấn đề: Làm thế nào để nhập tệp hoặc mô -đun từ một thư mục hoặc thư mục khác trong Python?: How to import a file or a module from another folder or directory in Python?

Ví dụ: Giả sử, bạn đã đưa ra cấu trúc thư mục sau:: Say, you’ve given the following folder structure:

application
 ├── app
 │   └── folder
 │       └── file_1.py
 └── app2
     └── some_folder
         └── file_2.py

Mục tiêu của bạn là nhập các chức năng từ

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
5 trong
import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
6.

Phương pháp 1: sys.path.append []

Phương pháp đầu tiên nối đường đường dẫn của biến

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
8 của hệ thống.

# file_2.py
import sys
sys.path.append['/.../application/app/folder']

import file_1

Lưu ý rằng bạn cần thay thế ba chấm đầu tiên trong

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
9 bằng đường dẫn bê tông đến thư mục

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
0.

Nhân tiện, vui lòng tham gia Học viện Email miễn phí của tôi và tải xuống các tờ Cheat Python của bạn tại đây:download your Python cheat sheets here:

Nó rất vui-và hàng ngàn Finxters đã nói với tôi rằng họ yêu thích các tờ che phủ!

Được rồi, hãy để Lừa chuyển sang một giải pháp sửa đổi một chút cho vấn đề này:

Phương pháp 2: sys.path.insert []

Một giải pháp thay thế tương tự là chèn đường dẫn của

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
5 vào vị trí 1 của biến hệ thống ____ ____18.

Điều này đảm bảo rằng nó được tải với mức độ ưu tiên cao hơn và tránh một số xung đột đặt tên:

# file_2.py
import sys
sys.path.insert[1, '/.../application/app/folder']

import file

Một lần nữa, thay thế ba chấm đầu tiên trong

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
9 bằng đường dẫn bê tông vào thư mục

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
0.

Phương pháp 3: Ký hiệu chấm với __init__.py

Bạn cũng có thể thực hiện các thủ thuật sau đây tạo ra một gói mới.

# file_2.py
from application.app.folder.file_1 import func_name

Tuy nhiên, hãy đảm bảo bao gồm một tệp

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
2 trống trong thư mục.

Tệp này bảo Python coi thư mục là một gói. Tôi đã coi đây là cách giải quyết vấn đề này.the most Pythonic way of solving this problem.

Phương pháp 4: Nhập khẩu

Một sự thay thế không phải là pythonic-nó có thể cồng kềnh hơn và dựa trên các phụ thuộc bên ngoài-sẽ là sử dụng mô-đun


['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6.

Đây là một ví dụ:

import importlib.util as ilu

folder = '/.../application/app/folder'
file = 'file_2'

spec = ilu.spec_from_file_location[file, folder]
your_lib = ilu.module_from_spec[spec]
spec.loader.exec_module[your_lib]

your_lib.function[]

Video liên quan

Vui lòng xem video giải thích sau trong đó người tạo Finxter Peter chỉ cho bạn cách gọi chức năng từ một tệp khác:Peter shows you how to call a function from another file:

Làm thế nào để gọi một hàm từ một tệp khác trong Python?

Người giới thiệu

  • //stackoverflow.com/questions/4383571/importing-files-from-different-folder
  • //stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?rq=1
  • Cách nhập chức năng Python từ một thư mục khác

Đi đâu từ đây?

Đủ lý thuyết. Hãy để có được một số thực hành!

Các lập trình viên được trả tiền sáu con số và hơn thế nữa vì họ có thể giải quyết các vấn đề hiệu quả hơn bằng cách sử dụng trí thông minh máy móc và tự động hóa.

Để trở nên thành công hơn trong việc mã hóa, giải quyết nhiều vấn đề thực sự hơn cho người thực. Đó là cách bạn đánh bóng các kỹ năng bạn thực sự cần trong thực tế. Rốt cuộc, những gì mà việc sử dụng lý thuyết học tập mà không ai cần?

Bạn xây dựng các kỹ năng mã hóa có giá trị cao bằng cách làm việc trên các dự án mã hóa thực tế!

Bạn có muốn ngừng học hỏi với các dự án đồ chơi và tập trung vào các dự án mã thực tế kiếm tiền cho bạn và giải quyết các vấn đề thực sự cho mọi người?

Nếu câu trả lời của bạn là có !, Hãy xem xét việc trở thành một nhà phát triển tự do Python! Đó là cách tốt nhất để tiếp cận nhiệm vụ cải thiện các kỹ năng trăn của bạn, ngay cả khi bạn là người mới bắt đầu hoàn toàn.YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Nếu bạn chỉ muốn tìm hiểu về cơ hội làm việc tự do, vui lòng xem hội thảo trên web miễn phí của tôi Làm thế nào để xây dựng kỹ năng thu nhập cao của bạn Python và tìm hiểu cách tôi phát triển kinh doanh mã hóa của mình trực tuyến và làm thế nào bạn có thể, từ sự thoải mái của bạn riêng nhà.

Tham gia hội thảo trên web miễn phí ngay bây giờ!

Nhiều hướng dẫn Finxter

Học tập là một quá trình liên tục và bạn sẽ khôn ngoan khi không bao giờ ngừng học hỏi và cải thiện trong suốt cuộc đời. 👑

Học gì? Tiềm thức của bạn thường biết rõ hơn tâm trí có ý thức của bạn những kỹ năng bạn cần để đạt đến cấp độ thành công tiếp theo. Your subconsciousness often knows better than your conscious mind what skills you need to reach the next level of success.

Tôi khuyên bạn nên đọc ít nhất một hướng dẫn mỗi ngày [chỉ 5 phút cho mỗi hướng dẫn là đủ] để đảm bảo bạn không bao giờ ngừng học!one tutorial per day [only 5 minutes per tutorial is enough] to make sure you never stop learning!

Nếu bạn muốn chắc chắn rằng bạn không quên thói quen của mình, hãy tham gia Học viện Email miễn phí của chúng tôi cho các hướng dẫn mới hàng tuần và nhắc nhở học tập trong hộp thư đến của bạn.

Ngoài ra, hãy lướt qua danh sách các hướng dẫn sau đây và mở 3 cái thú vị trong tab Trình duyệt mới để bắt đầu thói quen học tập mới - hiện tại của bạn ngay hôm nay! 🚀

Những điều cơ bản của Python:

  • Python một dòng cho vòng lặp
  • Nhập các mô -đun từ một thư mục khác
  • Xác định loại đối tượng Python
  • Chuyển đổi danh sách chuỗi thành danh sách int
  • Chuyển đổi danh sách INT thành danh sách chuỗi
  • Chuyển đổi danh sách chuỗi thành danh sách float
  • Chuyển đổi danh sách thành mảng numpy
  • Nối dữ liệu vào tệp JSON
  • Danh sách lọc Python
  • Danh sách lồng nhau

Quản lý phụ thuộc Python:

  • Cài đặt PIP
  • Cách kiểm tra phiên bản Python của bạn
  • Kiểm tra phiên bản Pandas trong tập lệnh
  • Kiểm tra phiên bản Python Jupyter
  • Kiểm tra phiên bản của gói PIP

Python gỡ lỗi:

  • Bắt và in ngoại lệ
  • Danh sách chỉ số vượt khỏi phạm vi
  • Khắc phục sự thật lỗi giá trị
  • Không thể nhập tên x lỗi

Công cụ thú vị:

  • 5 tấm cheat mọi lập trình viên python cần phải sở hữu
  • 10 Câu đố Python tốt nhất để khám phá trình độ kỹ năng thực sự của bạn
  • Làm thế nào để $ 1000 ở bên cạnh như một người làm việc tự do Python

Cảm ơn vì đã học với Finxter!

Lập trình viên hài hước

import importlib.util

def module_from_file[module_name, file_path]:
    spec = importlib.util.spec_from_file_location[module_name, file_path]
    module = importlib.util.module_from_spec[spec]
    spec.loader.exec_module[module]
    return module

foo = module_from_file["foo", "/path/to/foo.py"]

if __name__ == "__main__":
    print[foo]
    print[dir[foo]]
    foo.announce[]
0

Trong khi làm việc như một nhà nghiên cứu trong các hệ thống phân tán, Tiến sĩ Christian Mayer đã tìm thấy tình yêu của mình đối với việc dạy các sinh viên khoa học máy tính.

Để giúp học sinh đạt được thành công cao hơn của Python, ông đã thành lập trang web giáo dục chương trình Finxter.com. Ông là tác giả của cuốn sách lập trình phổ biến Python Oneer [Nostarch 2020], đồng tác giả của loạt sách Break Break Python, những cuốn sách tự xuất bản, người đam mê khoa học máy tính, freelancer và chủ sở hữu của một trong 10 blog Python lớn nhất trên toàn thế giới.

Niềm đam mê của ông là viết, đọc và mã hóa. Nhưng niềm đam mê lớn nhất của anh là phục vụ các lập trình viên đầy tham vọng thông qua Finxter và giúp họ tăng cường các kỹ năng của họ. Bạn có thể tham gia học viện email miễn phí của anh ấy ở đây.

Tại sao tôi cần __ init __ py?

Các tệp __init__.py được yêu cầu để làm cho các thư mục xử lý Python chứa tệp dưới dạng các gói.Điều này ngăn các thư mục có tên chung, chẳng hạn như chuỗi, vô tình ẩn các mô -đun hợp lệ xảy ra sau đó trên đường dẫn tìm kiếm mô -đun.to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.

__ init __ trong gói Python là gì?

Tệp __init__.py chỉ ra rằng các tệp trong thư mục là một phần của gói Python.Nếu không có tệp __init__.py, bạn không thể nhập các tệp từ một thư mục khác trong dự án Python.indicates that the files in a folder are part of a Python package. Without an __init__.py file, you cannot import files from another directory in a Python project.

Làm thế nào chúng ta có thể nhập tệp .py từ một thư mục khác?

Chúng ta có thể sử dụng sys.path để thêm đường dẫn của thư mục mới [thư mục từ nơi chúng ta muốn nhập các mô -đun] vào đường dẫn hệ thống để Python cũng có thể tìm mô -đun trong thư mục đó nếu nó không tìm thấyMô -đun trong thư mục hiện tại của nó.use sys. path to add the path of the new different folder [the folder from where we want to import the modules] to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

__ init __ py trống?

Để lại một tệp __init__.py trống được coi là bình thường và thậm chí là một thông lệ tốt, nếu các mô-đun và gói phụ của gói không cần phải chia sẻ bất kỳ mã nào. and even a good practice, if the package's modules and sub-packages do not need to share any code.

Bài Viết Liên Quan

Chủ Đề