我的目录结构如下:
MainDir --FooBar --foobar.py, __init__.py
|
Ltests -- foobartest.py, __init__.py
在 foobartest.py 中, 我正在导入
从 FooBar.foobar.func_in_foobar 导入 *
__init__.py in foobar contains from .foobar import *
init.py 在测试文件夹中是空的
但是当我尝试运行 foobartest 我得到这个错误
No module named FooBar.foobar.func_in_foobar
请您参考如下方法:
我认为您可以按照 Sorin 在此处的回答中的相同方式解决此问题 - https://stackoverflow.com/a/6098238/1491900 :
import os, sys, inspect
# realpath() with make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to include modules from a subforder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if script is called in different ways on Windows
# __file__ fails if someone does os.chdir() before
# sys.argv[0] also fails because it doesn't not always contains the path
