文件的相对路径没有得到解决

Relative path of file does not get solved

显然 python 获取与第一个调用文件相关的所有相关导入。

我有以下文件结构

src
 |--myunittests.py
 |--subfolder1
      |--__init__.py
      |--printFileContent.py
      |--subfolder2
           |--__init__.py
           |--file

myunittests.py 将测试 printFileContent:

中函数的行为
from subfolder1.printFileContent import printFileContent
printFileContent()

printFileContent 打印子文件夹中包含的文件的内容:

def printFileContent():
with open("./subfolder2/file") as file:
    for line in file:
        print(line)


if __name__ == "__main__":
    printFileContent()

文件 只包含一些文本。

问题: 在 subfolder1 中执行 python3 printFileContent.py 将正确输出文件内容。 但是做 python3 myunittests.py 会引发错误,找不到文件。

有办法解决这个问题吗? (有没有办法告诉 python,以编程方式相对引用的文件应该相对于它们在其中使用的文件?

约束

这种行为是什么时候发生的?file 是在 printFileContent.py 内部使用的图标时,而 printFileContent.py 是从 myunittests.py

调用的

附带问题: 是否有合适的 title/bulletpoint 词来解释/找出这种行为及其问题?

如果不能修改printFileContent.py,可以保存当前目录,到subfolder1的目录再回到原目录:

import subfolder1
import os

# Save current directory (absolute path)
cdir = os.path.abspath(os.path.curdir)

# Change directory, and call printFileContent
os.chdir(os.path.dirname(subfolder1.__file__))
subfolder1.printFileContent()

# Go back to the original directory
os.chdir(cdir)

如果你必须经常使用它,你可以使这个行为成为 class 可与 with 语句一起使用,这样它更容易使用并且更健壮(你不会忘记chdir回来了):

import os

class TmpDirChanger:
  def __init__(self, tmpPath):
    self.currentDir = os.path.abspath(os.path.curdir)
    os.chdir(tmpPath)

  def __enter__(self): pass

  def __exit__(self, exc_type, exc_val, exc_tb):
    #change back to original dir
    os.chdir(self.currentDir)

with TmpDirChanger('path/to/some/dir'):
   do_something()

如果能修改printFileContent.py,就没那么棘手了:

import os

def printFileContent():
    # This will give you path to subfolder1
    sfolder1 = os.path.dirname(__file__)

    # This will give you path to "file" in subfolder2
    name = os.path.join(sfolder1, 'subfolder2', 'file')

    with open(name) as file:
        for line in file:
            print(line)