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

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

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:

  1. TEST1.py
  2. |____________TEST2.py

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

With the following code inside of TEST1.py:

  1. import os
  2. CurrDirPath = os.path.dirname(__file__)
  3. CurrFileName = os.path.join(CurrDirPath, "../TEST2.py")
  4. import TEST2
  5. if (__name__ == '__main__'):
  6. print(TEST2.TEST3())

And the following code inside of TEST2.py:

  1. def TEST3():
  2. return "test"

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

  1. import TEST2
  2. 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:

  1. TEST1.py
  2. |____________TEST2.py

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

With the following code inside of TEST1.py:

  1. import os
  2. CurrDirPath = os.path.dirname(__file__)
  3. CurrFileName = os.path.join(CurrDirPath, "../TEST2.py")
  4. import TEST2
  5. if (__name__ == '__main__'):
  6. print(TEST2.TEST3())

And the following code inside of TEST2.py:

  1. def TEST3():
  2. return "test"

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

  1. import TEST2
  2. 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

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

如果您的文件排列如下:

  1. test1.py
  2. └──── sub_folder
  3. test2.py

以下代码应该可以工作:

  1. import os
  2. import sys
  3. CurrDirPath = os.getcwd()
  4. DesiredDirPath = CurrDirPath + os.sep + "sub_folder"
  5. sys.path.insert(1, DesiredDirPath)
  6. import TEST2
  7. if (__name__ == '__main__'):
  8. print(TEST2.TEST3())

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

  1. test2.py
  2. └──── sub_folder
  3. test1.py

以下代码应该可以工作:

  1. import os
  2. import sys
  3. CurrDirPath = os.getcwd()
  4. # 以下命令会返回上一级目录
  5. DesiredDirPath = os.path.normpath(CurrDirPath + os.sep + os.pardir)
  6. sys.path.insert(1, DesiredDirPath)
  7. import TEST2
  8. if (__name__ == '__main__'):
  9. 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:

  1. test1.py
  2. └──── sub_folder
  3. test2.py

Below Code should work:

  1. import os
  2. import sys
  3. CurrDirPath = os.getcwd()
  4. DesiredDirPath = CurrDirPath + os.sep + "sub_folder"
  5. sys.path.insert(1, DesiredDirPath)
  6. import TEST2
  7. if (__name__ == '__main__'):
  8. print(TEST2.TEST3())

But, if your files arranged like this:

  1. test2.py
  2. └──── sub_folder
  3. test1.py

Below Code should work:

  1. import os
  2. import sys
  3. CurrDirPath = os.getcwd()
  4. # Below command, goes one folder back
  5. DesiredDirPath = os.path.normpath(CurrDirPath + os.sep + os.pardir)
  6. sys.path.insert(1, DesiredDirPath)
  7. import TEST2
  8. if (__name__ == '__main__'):
  9. 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 位于子文件夹中,例如:

  1. test1.py
  2. └──── sub_folder
  3. test2.py

那么对于 test1.py

  1. import os
  2. import importlib.util
  3. import sys
  4. CurrDirPath = os.path.dirname(__file__)
  5. CurrFileName = os.path.join(CurrDirPath, r"sub_folder\test2.py")
  6. spec = importlib.util.spec_from_file_location("test2", CurrFileName)
  7. test2 = importlib.util.module_from_spec(spec)
  8. sys.modules["module.name"] = test2
  9. spec.loader.exec_module(test2)
  10. if __name__ == '__main__':
  11. print(test2.test3())

test2.py 中:

  1. def test3():
  2. 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:

  1. test1.py
  2. └──── sub_folder
  3. test2.py

So for test1.py:

  1. import os
  2. import importlib.util
  3. import sys
  4. CurrDirPath = os.path.dirname(__file__)
  5. CurrFileName = os.path.join(CurrDirPath, r"sub_folder\test2.py")
  6. spec = importlib.util.spec_from_file_location("test2", CurrFileName)
  7. test2 = importlib.util.module_from_spec(spec)
  8. sys.modules["module.name"] = test2
  9. spec.loader.exec_module(test2)
  10. if __name__ == '__main__':
  11. print(test2.test3())

In test2.py:

  1. def test3():
  2. 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:

确定