从上述文件夹导入python文件时出现问题

问题描述 投票:0回答:2

我知道有很多问题和答案,我尝试了许多stackoverflow链接,但这些似乎都没有帮助。

我的项目结构是:

volume_price_analysis/
  README.md
  TODO.md
  build/
  docs/
  requirements.txt
  setup.py
  vpa/
    __init__.py
    database_worker.py
    utils.py
    test/
      __init__.py
      test_utils.py
      input/
        input_file.txt

我想在test_utils.py中加载utils.py

我的test_utils.py是:

import unittest
import logging
import os

from .vpa import utils

class TestUtils(unittest.TestCase):

    def test_read_file(self):
        input_dir = os.path.join(os.path.join(os.getcwd()+"/test/input"))
        file_name = "input_file.txt"

        with open(os.path.join(input_dir+"/"+file_name)) as f:
            file_contents = f.read()
        f.close()

        self.assertEqual(file_contents, "Hello World!\n")

if __name__ == '__main__':
    unittest.main()

我要运行(例如在test文件夹中):

python3 -m test_utils.py

[我做不到,我在导入utils时遇到一堆错误(尝试了多次从。,no。的迭代,等等。

为什么这么血腥复杂?

如果有帮助,我正在使用Python 3.7。

python-3.x
2个回答
0
投票

根据this的答案,您可以使用importlib来完成,

spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")中,您可以使用path/to/file代替../utils.py。另外,由于您已经从importlib导入了一个名为utils的程序包,因此应使用其他名称调用其中一个。不要将module.name保留为utils或将importlib.utils保留为其他名称。


0
投票

[我知道了,结果发现python希望您从顶层文件夹运行代码,在我的情况下是volume_price_analysis文件夹,我要做的就是制作一个可调用的Shell脚本

python3 -m unittest vpa.test.test_utils

test_utils内部,我可以导入任何我想输入的内容,只要我记得我正在执行主文件夹中的代码,这样就可以加载utils.py

from vpa import utils在test_utils内部

© www.soinside.com 2019 - 2024. All rights reserved.