包括文件相对路径中的函数(Python 3.10)

huangapple go评论65阅读模式
英文:

Include Functions from File Relative Path (Python 3.10)

问题

I'm attempting to include & call Python functions from a different py file, by providing a relative file path to the os.path.join function call.

Let's say I have two py files, TEST1.py and TEST2.py, and a function defined inside of TEST2.py called TEST3().

Alongside the following directory structure:

TEST1.py
|____________TEST2.py

So TEST1.py is located one directory above TEST2.py.

With the following code inside of TEST1.py:

import os

CurrDirPath = os.path.dirname(__file__)
CurrFileName = os.path.join(CurrDirPath, "../TEST2.py")

import TEST2

if (__name__ == '__main__'):
    print(TEST2.TEST3())

And the following code inside of TEST2.py:

def TEST3():
    return "test"

Results in the following exception upon attempting to run TEST1.py:

   import TEST2
ModuleNotFoundError: No module named 'TEST2'

What is the proper way to include Python functions from a relative file path?

Thanks for reading my post, any guidance is appreciated.

英文:

I'm attempting to include & call Python functions from a different py file, by providing a relative file path to the os.path.join function call.

Let's say I have two py files, TEST1.py and TEST2.py, and a function defined inside of TEST2.py called TEST3().

Alongside the following directory structure:

TEST1.py
|____________TEST2.py

So TEST1.py is located one directory above TEST2.py.

With the following code inside of TEST1.py:

import os

CurrDirPath = os.path.dirname(__file__)
CurrFileName = os.path.join(CurrDirPath, "../TEST2.py")

import TEST2

if (__name__ == '__main__'):
    print(TEST2.TEST3())

And the following code inside of TEST2.py:

def TEST3():
    return "test"

Results in the following exception upon attempting to run TEST1.py:

   import TEST2
ModuleNotFoundError: No module named 'TEST2'

What is the proper way to include Python functions from a relative file path?

Thanks for reading my post, any guidance is appreciated.

答案1

得分: 1

以下是您要翻译的代码部分:

如果您的文件排列如下:

│   test1.py
│
└──── sub_folder
      │   test2.py

以下代码应该可以工作:

import os
import sys

CurrDirPath = os.getcwd()
DesiredDirPath = CurrDirPath + os.sep + "sub_folder"    

sys.path.insert(1, DesiredDirPath)

import TEST2

if (__name__ == '__main__'):
    print(TEST2.TEST3())

但是,如果您的文件排列如下:

│   test2.py
│
└──── sub_folder
      │   test1.py

以下代码应该可以工作:

import os
import sys

CurrDirPath = os.getcwd()
# 以下命令会返回上一级目录
DesiredDirPath = os.path.normpath(CurrDirPath + os.sep + os.pardir)    

sys.path.insert(1, DesiredDirPath)

import TEST2

if (__name__ == '__main__'):
    print(TEST2.TEST3())

首先,您需要获取所需的工作目录,然后通过以下代码在运行时将此路径添加到系统的已知路径中:
sys.path.insert(1, DesiredDirPath)

现在您可以导入TEST2。

在下面的链接中有相关讨论:
https://stackoverflow.com/questions/4383571/importing-files-from-different-folder

英文:

if your files arranged like this:

│   test1.py
│
└──── sub_folder
      │   test2.py

Below Code should work:

import os
import sys

CurrDirPath = os.getcwd()
DesiredDirPath = CurrDirPath + os.sep + "sub_folder"    

sys.path.insert(1, DesiredDirPath)

import TEST2

if (__name__ == '__main__'):
    print(TEST2.TEST3())

But, if your files arranged like this:

│   test2.py
│
└──── sub_folder
      │   test1.py

Below Code should work:

import os
import sys

CurrDirPath = os.getcwd()
# Below command, goes one folder back
DesiredDirPath = os.path.normpath(CurrDirPath + os.sep + os.pardir)    

sys.path.insert(1, DesiredDirPath)

import TEST2

if (__name__ == '__main__'):
    print(TEST2.TEST3())

first you need to get Desired working directory and Then you need to add this path to known paths of the system, clearly at runtime, by this code:
sys.path.insert(1, DesiredDirPath)

Now you can import TEST2

There is nice discussion at below link:
https://stackoverflow.com/questions/4383571/importing-files-from-different-folder

答案2

得分: 0

你可以使用 importlib

如果 test2.py 位于子文件夹中,例如:

│   test1.py
└──── sub_folder
      │   test2.py

那么对于 test1.py

import os
import importlib.util
import sys

CurrDirPath = os.path.dirname(__file__)
CurrFileName = os.path.join(CurrDirPath, r"sub_folder\test2.py")

spec = importlib.util.spec_from_file_location("test2", CurrFileName)
test2 = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = test2
spec.loader.exec_module(test2)

if __name__ == '__main__':
    print(test2.test3())

test2.py 中:

def test3():
    return 'test2'

更多详细信息,请参阅答案:https://stackoverflow.com/questions/67631/how-can-i-import-a-module-dynamically-given-the-full-path

英文:

You can use importlib

If test2.py in located in subfolder, for example:

│   test1.py
│
└──── sub_folder
      │   test2.py

So for test1.py:

import os
import importlib.util
import sys


CurrDirPath = os.path.dirname(__file__)
CurrFileName = os.path.join(CurrDirPath, r"sub_folder\test2.py")

spec = importlib.util.spec_from_file_location("test2", CurrFileName)
test2 = importlib.util.module_from_spec(spec)
sys.modules["module.name"] = test2
spec.loader.exec_module(test2)

if __name__ == '__main__':
    print(test2.test3())

In test2.py:

def test3():
    return 'test2'

More details in answer https://stackoverflow.com/questions/67631/how-can-i-import-a-module-dynamically-given-the-full-path

huangapple
  • 本文由 发表于 2023年6月25日 18:35:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76549976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定