Python import自定义模块报错、自定义异常、字符串处理、截取

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

一、python import自定义的模块报错

问题现象pycharm中运行一切正常但是到命令行中cmd命令行或pycharm的Terminal窗口运行py文件就会报错No module named xxx

问题原因
pycharm在每次运行时都会检索整个工程目录把目录都添加到sys.path中运行的时候就能够找到对应的模块.py文件。命令行运行时由于目录没有添加到sys.path中所以会报错No module named xxx

解决方案
比如order.py文件中引入了http_utils.pyorder.py、http_utils.py文件在项目中的目录结构如下

根目录
----utils
-------http_utils.py
----testcases
-------mainprocess
-----------order.py

则在order.py文件中头部添加以下代码

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from utils.http_utils import *

其中os.path.abspath(file)用来获取本文件的绝对路径os.path.dirname用来获取参数的直接全路径。

可以理解通过这段代码定义了order.py需要向上找3层就找到项目根目录所以这里要写3个os.path.dirname。找到根目录后才能正常的从utils目录找到http_utils.py因此就不会再报错No module named xxx

二、python 自定义异常

实际工作中有太多的场景是内置的异常所触及不到的而这时候使用我们自己定义的异常类型就可以更好的打通业务。自定义异常代码如下

# 自定义异常
class XError(Exception):
    def __init__(self, value=""):  # 在抛出一个异常的时候可以传一个值进来
        self.value = value

    # 用来print异常信息
    def __str__(self):
        return "XError " + str(self.value)

使用举例在接口测试代码中使用自定义异常判断当接口返回的code值不为1时就抛出异常

def interfaceRequest():
    headers = {
        "Accept-Encoding": "gzip, deflate, br"
    }

    url = 'https://nc.cli.im/qrcode/getDefaultComponentMsg'

    print("开始测试接口interfaceRequest")
    print("接口请求url" + url)
    logging.info("接口请求url" + url)
    res = requests.get(url, headers=headers)
    print("接口返回结果" + res.text)
    code = json.loads(res.text).get("code")
    print("code值" + str(code))
    if str(code) == "1":
        pass
    else:
        raise XError("接口返回值不等于预期值接口返回结果" + res.text)

三、Python返回字符串中第一个不重复的字母和位置

这是一道常见的测开面试题验证面试者对python基础语法的熟悉程度解题代码如下

def first_char(str):
    d = {}
    for i in range(len(str)):
        # 累计字符的出现次数
        if str[i] in d:
            d[str[i]] += 1
        # 只出现一次key对应的value就记1次
        else:
            d[str[i]] = 1
    for i in range(len(str)):
        if d[str[i]] == 1:
            return '第一个不重复的字符串是{},索引是{}'.format(str[i], i)

    return "没有不重复的字符串"


if __name__ == '__main__':
    s = "wwqqooagg"
    res = first_char(s)
    print(res)

测试结果如下
在这里插入图片描述

四、Python根据指定开头和结尾截取字符串

编写接口自动化测试代码时有的时候我们需要提取一段字符串中的某一部分字符用作后续接口使用代码如下

def GetMiddleStr(self, content, startStr, endStr):
    """
    提取testcase的名字用于log目录使用
    """
    startIndex = content.index(startStr)
    if startIndex >= 0:
        startIndex += len(startStr)
    endIndex = content.index(endStr)
    return content[startIndex:endIndex]
    
if __name__=='__main__':
    content= "D:\pycharmProject\autotest\testcases\order\cancelOrder.air"
    startStr="order\\"
    endStr=".air"
    testcaseName=self.GetMiddleStr(content,startStr,endStr)
   

最后得到的字符串是cancelOrder

==============================================================================
以上就是本次的全部内容都看到这里了如果对你有帮助麻烦下方点击名片关注持续分享全栈测试知识干货你的支持就是作者更新最大的动力~

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: python