在导入的模块中打开文件

时间:2020-06-30 19:11:07

标签: python file import

  1. 假设我具有这样的项目结构:
    project \
        package1 \
            file1.py
        package2 \
            file2.py
  1. package1.file1.py中,我有类似的东西
arguments_path = 'some_relative_path'
instance = SomeClass(arguments_path)
  1. package2.file2.py中,我要从第一个包中导入文件: from project.package1 import file1。但是由于我在运行时路径FileNotFoundError无效,所以我偶然有了'some_relative_path'。它开始看起来像path_that_i_need\package2
  2. 我尝试使用absolutepathrealpath,但他们也无法解决。而且我无法对some_relative_path变量进行硬编码,因为此代码将在大量容器和服务上运行,因此将取决于运行它的机器。

希望您能帮助我。还是谢谢你!

编辑:

跟踪:

File "/home/lightningseas/mammography/service_inference/model/tests/test_inference.py", line 7, in <module>
    import service_inference.model.inference as inference
File "/home/lightningseas/mammography/service_inference/__init__.py", line 10, in <module>
    segmentation.load_state_dict(torch.load('./weights/segmentation.pth'))
File "/home/lightningseas/.local/lib/python3.7/site-packages/torch/serialization.py", line 419, in load
    f = open(f, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: './weights/segmentation.pth'

文件结构:

service_inference \
      model \
         __init.py__
        other_files.py
        tests \
            test_inference.py
            other_tests.py
        weights \
            segmentation.pth

__init.py__中:

segmentation = Segmentation(1, 1)
segmentation = segmentation.cuda()
segmentation.load_state_dict(torch.load('./weights/segmentation.pth'))

test_inference.py中,我从模型中导入了一些文件。 不在tests目录中使用它就可以了。

0 个答案:

没有答案