我就废话不多说了,大家往下看吧~
P
|-A
| a.py
|-B
| b.py
文件结构如上,在windows下
a想运行b中的方法,可以直接写成
from B impot bb.fun()
但是在linux中会出现
ModuleNotFoundError: No module named \’B\’
可以通过引入sys添加路径解决
import syssys.path.append(\"/P/B\")from B impot b
在程序中为了也有良好的移植性,可以在代码中显式添加路径,
比如用os的方法:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
或者pathlib 方法:
BASE_DIR = Path(__file__).resolve().parent.parent
最后可以添加到 sys.path中
sys.path.append(str(BASE_DIR))
补充:python import导入三种方式(导入不同文件夹的文件,window和linux的区别)
import导入方式
1、导入python自有的库
import json
2、导入同级目录下的文件,比如在logindev.py导入read_config.py文件
# coding = utf-8from read_config import ReadConfigimport requestsimport json# 拼接请求参数,获取cookie,作为后续登录使用
3、导入不同级别目录下的文件:
a、windows环境
# coding = utf-8import datetimeimport allureimport pytestimport jsonimport sys\"\"\"windows执行的时候,直接在系统路径上新增文件夹路径\"\"\"sys.path.append(\"../common\")\"\"\"linux执行的时候,直接按照相对路径引用即可\"\"\"from common import http_request
这段代码在linux下报如下错误:
==================================== ERRORS ====================================_______________ ERROR collecting test_case/test_member_ticket.py _______________ImportError while importing test module \'/var/jenkins_home/workspace/pytest_allure/test_case/test_member_ticket.py\'.Hint: make sure your test modules/packages have valid Python names.Traceback:test_member_ticket.py:8: in <module>from common import http_requestE ImportError: No module named \'common\'
b、linux环境
# coding = utf-8import datetimeimport allureimport pytestimport jsonimport sys\"\"\"windows执行的时候,直接在系统路径上新增文件夹路径\"\"\"#sys.path.append(\"../common\")\"\"\"linux执行的时候,直接按照相对路径引用即可\"\"\"from ..common import http_request
这段代码在windows报如下错误:
========================================================================== ERRORS ==========================================================================__________________________________________________________ ERROR collecting test_member_ticket.py __________________________________________________________test_member_ticket.py:8: in <module>from ..common import http_requestE ValueError: attempted relative import beyond top-level package================================================================= short test summary info ==================================================================ERROR test_member_ticket.py - ValueError: attempted relative import beyond top-level package!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!===================================================================== 1 error in 0.46s =====================================================================
以上为个人经验,希望能给大家一个参考如有错误或未考虑完全的地方,望不吝赐教。
您可能感兴趣的文章:
- Python在Windows和在Linux下调用动态链接库的教程
- Python在不同目录下导入模块的实现方法
- Python3导入自定义模块的三种方法详解