外部文件夹中的参考模块

问题描述 投票:0回答:1
我正在开发一个名为“py_lopa”的模块。通常,在开发它时,我会在“py_lopa”上一层的超级文件夹中编写一个小脚本,并从那里运行它。但是,这个较高的文件夹中充满了小文件。

我想以某种方式将脚本移动到与“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”模块?

python module
1个回答
0
投票
您可以使用 sys.path.append(),如下所示。 假设 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'])
    
© www.soinside.com 2019 - 2024. All rights reserved.