欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python import导入三种方式(导入不同文件夹的文件,window和linux的区别)

程序员文章站 2022-07-07 20:09:58
import导入方式1、导入python自有的库import json2、导入同级目录下的文件,比如在logindev.py导入read_config.py文件# coding = utf-8from read_config import ReadConfigimport requestsimport json# 拼接请求参数,获取cookie,作为后续登录使用3、导入不同级别目录下的文件:a、windows环境# coding = utf-8import datetimeim...

import导入方式

1、导入python自有的库
import json
2、导入同级目录下的文件,比如在logindev.py导入read_config.py文件
python  import导入三种方式(导入不同文件夹的文件,window和linux的区别)

# coding = utf-8
from read_config import ReadConfig
import requests
import json
# 拼接请求参数,获取cookie,作为后续登录使用

3、导入不同级别目录下的文件:
a、windows环境

# coding = utf-8
import datetime
import allure
import pytest
import json
import 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_request
E   ImportError: No module named 'common'

b、linux环境

# coding = utf-8
import datetime
import allure
import pytest
import json
import 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_request
E   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 =====================================================================

本文地址:https://blog.csdn.net/liucaimei_0327/article/details/107183025