我想以某种方式将脚本移动到与“py_lopa”同一级别的子文件夹中。但是,我不确定如何从另一个文件夹引用 py_lopa 模块。
结构示例:
"src_code" (highest level folder)
"py_lopa" (sub-folder - contains entire module)
"scripts_for_testing" (sub-folder - want to move all "test_script.py" files here)
"test_script_001.py"
"test_script_002.py"
.
.
.
在 test_script 文件之一内,它当前根据需要导入 py_lopa 模块:
from py_lopa.model_interface import Model_Interface
from py_lopa.data.tests_enum import Tests_Enum
from py_lopa.data.tables import Tables
.
.
.
但是,如果我将 test_script 文件移动到“scripts_for_testing”文件夹,我将无法引用 py_lopa 模块。如何从“scripts_for_testing”文件夹内的脚本引用“py_lopa”模块?
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from py_lopa.model_interface import Model_Interface
print(sys.modules.keys())
以下是文件结构和输出。请注意,您可以从您想要的任何路径/位置执行 test.py 脚本。
~/work_area/python/tmp :-)> tree .
.
|-- py_lopa
| `-- model_interface
| `-- Model_Interface.py
`-- scripts_for_testing
`-- test.py
3 directories, 2 files
~/work_area/python/tmp :-)> python3 scripts_for_testing/test.py
dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'posixpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'sysconfig', '_sysconfigdata_m_linux_x86_64-linux-gnu', 'py_lopa', 'py_lopa.model_interface', 'py_lopa.model_interface.Model_Interface'])
~/work_area/python/tmp :-)> cd scripts_for_testing
~/work_area/python/tmp/scripts_for_testing :-)> python3 test.py
dict_keys(['builtins', 'sys', '_frozen_importlib', '_imp', '_warnings', '_thread', '_weakref', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'zipimport', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_weakrefset', 'site', 'os', 'errno', 'stat', '_stat', 'posixpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', 'sysconfig', '_sysconfigdata_m_linux_x86_64-linux-gnu', 'py_lopa', 'py_lopa.model_interface', 'py_lopa.model_interface.Model_Interface'])