Python调用另一个脚本时如何导入模块

3
我有以下Python结构目录结构。
在login_logout_test.py中,我使用以下导入语句,当我运行此脚本时一切正常(所有模块都已正确导入)。
import sys, os
parentPath = os.path.abspath("..")
if parentPath not in sys.path:
    sys.path.insert(0, parentPath)
import common_test_functions as cts
from functions import login_logout_functions as llf

但是当这个脚本(login_logout_test.py)被CommandRunner.py调用时,会出现以下错误:

没有找到名为'common_test_functions'的模块


当脚本被CommandRunner.py调用时,父目录是相对于CommandRunner.py的,而不是login_logout_test.py的父目录。 - EvanL00
我明白,但是我想以这样的方式导入脚本,使得 login_logout_test.py 单独运行或由 CommandRunner.py 调用时都能正常运行。 - stefan.stt
尝试使用一个点而不是两个。 - EvanL00
仍然不起作用。我以为如果包含父文件夹,这个导入from tests import common_test_functions as cts就会起作用,但实际上并没有。错误:_ModuleNotFoundError: No module named 'tests'_。 - stefan.stt
1个回答

2

实际上,我已经想出了解决自己问题的方案:

import sys, os
from selenium import webdriver
# adding path to common_test_functions to the sys.path
# so this module could be invoked
parentPath = os.path.abspath("..\\..")
if parentPath not in sys.path:
        sys.path.append(parentPath)
from functions import login_logout_functions as llf
from tests import common_test_functions as cts

还有一个文件,保存着脚本所需的参数。以下是获取该文件路径的代码,在两种情况下都可以使用(单独运行该脚本或由其他脚本调用):

parameters_directory_path = os.path.dirname(os.path.realpath(__file__))
parameters_file_name = "login_logout_test_parameters.tsv"
parameters_file_path = os.path.join(parameters_file_path, parameters_file_name)

如果有更好的,欢迎发表。谢谢你提前的帮助,斯特凡。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接