我就废话不多说了,大家往下看吧~ P |-A | a.py |-B | b.py 文件结构如上,在windows下 a想运行b中的方法,可以直接写成 from B impot b b.fun() 但是在li
我就废话不多说了,大家往下看吧~
P
|-A
| a.py
|-B
| b.py
a想运行b中的方法,可以直接写成
from B impot b
b.fun()
ModuleNotFoundError: No module named 'B'
可以通过引入sys添加路径解决
import sys
sys.path.append("/P/B")
from B impot b
在程序中为了也有良好的移植性,可以在代码中显式添加路径,
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = Path(__file__).resolve().parent.parent
最后可以添加到 sys.path中
sys.path.append(str(BASE_DIR))
补充:python import导入三种方式(导入不同文件夹的文件,window和linux的区别)
import导入方式
import JSON
# coding = utf-8
from read_config import ReadConfig
import requests
import json
# 拼接请求参数,获取cookie,作为后续登录使用
# 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'
# 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 =====================================================================
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。如有错误或未考虑完全的地方,望不吝赐教。
--结束END--
本文标题: 聊聊python在linux下与windows下导入模块的区别说明
本文链接: https://lsjlt.com/news/11610.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0