Hướng dẫn python 2.7 import module from another directory - python 2.7 nhập mô-đun từ một 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à 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:

<module 'foo' from '/path/to/foo.py'>
['__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:

<module 'bar' from '/path/to/foo.py'>
['__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:

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;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. 

Trong Linux, chúng ta có thể sử dụng lệnh sau trong thiết bị đầu cuối để đặt đường dẫn:A module is just a Python program that ends with .py extension and a folder that contains a module becomes a package.

Xuất pythonpath = đường dẫn/đến/thư mục

 - Folder_1
    - main.py
 - Folder_2
     - module1.py

Trong hệ thống Windows:

Đặt pythonpath = đường dẫn/đến/thư mục trực tuyến 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

Để 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

Sử dụng Pythonpath

Giả sử chúng ta có một cấu trúc thư mục như thế này:

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9
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

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
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()
2
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
6
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
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

baz = module_from_file("bar", "/path/to/foo.py")

if __name__ == "__main__":
    print(baz)
    print(dir(baz))
    baz.announce()
7
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

Bây giờ, bạn muốn nhập mô -đun mới.py từ thư mục_2 vào tệp dự án của chúng tôimodule1 from Folder_2, we will be encountering the following error.

main.py

Python3

& nbsp; từ project.folder.subfolder.filename nhập chức năng

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2
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

Output:

Hướng dẫn python 2.7 import module from another directory - python 2.7 nhập mô-đun từ một thư mục khác

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4 def9
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 add(a, b):1

Đầu ra, 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

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5
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
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

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
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
0
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
3
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.py
5
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2
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

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
0
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
1
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
5

Output::

Hướng dẫn python 2.7 import module from another directory - python 2.7 nhập mô-đun từ một thư mục khác

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

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
5
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
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
5
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
2
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

<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
7
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
8
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
0
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
1
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
1
- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py
5

Output:

Hướng dẫn python 2.7 import module from another directory - python 2.7 nhập mô-đun từ một thư mục khác

Sử dụng Pythonpath

Giả sử chúng ta có một cấu trúc thư mục như thế này:

- project
    - Folder_1
        - main.py
    - Folder_2
        - subfolder
            - new.py

Bây giờ, bạn muốn nhập mô -đun mới.py từ thư mục_2 vào tệp dự án của chúng tôi new.py module from Folder_2 to our project’s Folder_1 main.py file.

Syntax:

& nbsp; từ project.folder.subfolder.filename nhập chức năng

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
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
9

 - Folder_1
    - main.py
 - Folder_2
     - module1.py
0
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4
 - Folder_1
    - main.py
 - Folder_2
     - module1.py
2def6
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

<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
4 def9
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 add(a, b):1

add(a, b):2

Output:

Hướng dẫn python 2.7 import module from another directory - python 2.7 nhập mô-đun từ một thư mục khác

Đầu ra