我有以下 python structure directory structure
在 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
调用时,会出现此错误:
No module named 'common_test_functions'
最佳答案
其实我已经想出了解决我自己问题的办法:
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)
如果有人有更好的,请发布。
提前谢谢你。
斯特凡
关于另一个脚本调用脚本时Python导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42481054/