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à foo.py
:
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:
Trong khi làm việc trên các dự án lớn, chúng tôi có thể đối mặt với một tình huống mà chúng tôi muốn nhập một mô -đun từ một thư mục khác. Nhưng vì một số lý do, mô -đun có thể không được nhập chính xác. Bây giờ đừng lo lắng nếu mô -đun của bạn không được nhập chính xác. Trong bài viết này, chúng tôi sẽ thảo luận về các cách để nhập một mô -đun từ một thư mục khác. & NBSP;module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory.
Lưu ý: Một mô -đun chỉ là một chương trình Python kết thúc bằng phần mở rộng .py và một thư mục chứa một mô -đun trở thành một gói.A module is just a Python program that ends with .py extension and a folder that contains a module becomes a package.
Cấu trúc thư mục:
- Folder_1 - main.py - Folder_2 - module1.py
Hãy giả sử, để nhập cách nhập tệp trong Python, chúng tôi có hai thư mục khác nhau, một có chứa Main.py là tệp Python chính của chúng tôi nơi chúng tôi muốn nhập Module1 từ thư mục_2. & NBSP;
MODULE1: Chứa hai hàm gọi là Thêm và ODD_EVEN. Chức năng Thêm sẽ có hai đối số và trả về việc bổ sung chúng. Hàm ODD_EVEN sẽ chỉ lấy một đối số và in ngay cả khi số chẵn hoặc in lẻ nếu số là lẻ. contains two functions called add and odd_even. The function add will takes two arguments and return the addition of them. The odd_even function will take only one argument and print Even if the number is even or print Odd if the number is odd.
module1.py
Python3
def
add[a, b]:
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____11 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[]
2import 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[]
3import 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[]
4def
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
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[]
0import 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 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
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9import 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[]
0import 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[]
0import 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[]
2
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8import 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[]
7import 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[]
0Nếu chúng ta chỉ cần cố gắng nhập Module1 từ thư mục_2, chúng ta sẽ gặp phải lỗi sau.module1 from Folder_2, we will be encountering the following error.
main.py
Python3
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[]
9
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2import 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[]
0
Output:
Lỗi
ModulenotFounderRor, bởi vì theo mặc định, trình thông dịch Python sẽ chỉ kiểm tra tệp trong thư mục hiện tại và chúng tôi cần đặt đường dẫn tệp theo cách thủ công để nhập các mô -đun từ một thư mục khác. Chúng ta có thể làm điều này bằng cách sử dụng nhiều cách khác nhau. Những cách này được thảo luận dưới đây chi tiết., because by default Python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail.
Phương pháp 1: Nhập mô -đun từ các thư mục khác nhau bằng mô -đun SYS
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ấy mô -đun trong thư mục hiện tại của nó. Khi sys.Path thuộc lớp loại danh sách để, chúng ta có thể dễ dàng sử dụng phương thức chèn để thêm đường dẫn thư mục.sys.pathto 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. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.
Python3
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5import 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[]
9
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7import 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[]
9
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9- Folder_1 - main.py - Folder_2 - module1.py0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4- Folder_1 - main.py - Folder_2 - module1.py2
- Folder_1 - main.py - Folder_2 - module1.py3
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[]
0- Folder_1 - main.py - Folder_2 - module1.py5
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2import 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[]
0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8- project - Folder_1 - main.py - Folder_2 - subfolder - new.py0
- project - Folder_1 - main.py - Folder_2 - subfolder - new.py1
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1- Folder_1 - main.py - Folder_2 - module1.py2
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1- project - Folder_1 - main.py - Folder_2 - subfolder - new.py5
Output::
Sử dụng SYS
Phương pháp 2: Sử dụng biến PythonPathEnv môi trường environment variable
Tương tự, nếu bạn không muốn sử dụng mô -đun SYS để đặt đường dẫn của thư mục mới. Bạn có thể gán một đường dẫn thư mục cho biến PythonPath và vẫn giúp chương trình của bạn hoạt động. & NBSP;sys module to set the path of the new directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.
Trong Linux, chúng ta có thể sử dụng lệnh sau trong thiết bị đầu cuối để đặt đường dẫn:
Xuất pythonpath = đường dẫn/đến/thư mục
Trong hệ thống Windows:
Đặt pythonpath = đường dẫn/đến/thư mục trực tuyến
Để xem liệu biến PythonPath có giữ đường dẫn của thư mục mới hay không, chúng ta có thể sử dụng lệnh sau:
Echo $ Pythonpath
Python3
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5import 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[]
9
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7- Folder_1 - main.py - Folder_2 - module1.py5
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2import 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[]
0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8- project - Folder_1 - main.py - Folder_2 - subfolder - new.py0
- project - Folder_1 - main.py - Folder_2 - subfolder - new.py1
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1- Folder_1 - main.py - Folder_2 - module1.py2
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1- project - Folder_1 - main.py - Folder_2 - subfolder - new.py5
Output:
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[]
9
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9Sử dụng SYS
- project - Folder_1 - main.py - Folder_2 - subfolder - new.py
Phương pháp 2: Sử dụng biến PythonPathEnv môi trường new.py module from Folder_2 to our project’s Folder_1 main.py file.
Syntax:
Tương tự, nếu bạn không muốn sử dụng mô -đun SYS để đặt đường dẫn của thư mục mới. Bạn có thể gán một đường dẫn thư mục cho biến PythonPath và vẫn giúp chương trình của bạn hoạt động. & NBSP;
Python3
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[]
9
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9- Folder_1 - main.py - Folder_2 - module1.py0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4- Folder_1 - main.py - Folder_2 - module1.py2
def
6import 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[]
0Sử dụng SYS
add[a, b]:
2
Output:
Phương pháp 2: Sử dụng biến PythonPathEnv môi trường