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

标签 python path

我有以下 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/

相关文章:

java - 更改 JFileChooser 的目录

python - 如何在 python 中重复一个操作以使我的代码更简单

python - 将一个字符串分成一定长度的较小字符串列表

python - 使用多种符号在夏令时期间本地化 Pandas 日期时间

path - Neo4j 查找路径但没有某个节点

java - FileUploader - 在项目中保存数据

Android - 如何使用绘画连接两点

python - TensorFlow Iris load_csv_with_header( )

python - 向大型 python 项目添加单元测试

html - 文件 :///for url path for local html files?