python-python记录

python 掉坑记录
更多的 实践 及 工具 在 test_script/python 目录下
w3schools python - https://www.w3schools.com/python/default.asp


前篇


书单


技巧


新特性

3.8


3.7


3.6


python 升级

下载地址: https://www.python.org/downloads/

  1. 安装解释器, 并配到环境变量 (习惯将 3.x 版本的解释器改名为 python3.exe), 查看版本

    1
    2
    $ python3 -V
    Python 3.8.5
  2. 升级 pip, 命令

    1
    $ python3 -m pip install --upgrade pip
    • 不升级直接 pip3 install 各自库会出现以下问题
      1
      Fatal error in launcher: Unable to create process using

类型注解

这个是 python3 的特性, 可以指定类型, 编代码时可以有提示

1
2
self.srcDeps: dict = utils.loadJson(srcPath)["dependencies"]  # 指定类型 : dict
for k, v in self.srcDeps.items():

引入父级目录

这个的意思和 lua 差不多, 都是一个搜索路径的问题, 根据当前执行的环境添加相对的目录即可. 参考: import_test2.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import os

"""
要在任意地方执行某个脚本, 且需要使用到上级目录的脚本, 需要以下几个
"""

SelfPath = sys.path[0]
os.chdir(SelfPath) # 1. 环境先 cd 到当前脚本目录下
sys.path.append("..") # 2. 环境目录增加上一级目录搜索 (类似lua中增加一个搜索路径的意思)

from subpackage2 import module_z as mz # 3. 就可以搜索到 subpackage2 文件夹下的 module_z.py


if __name__ == "__main__":
mz.hello()

assert 断言:

正确写法

1
assert False, "--- wolegequ error" # 正确.

object dict 互转

  • object -> dict

    对象实例的 __dict__ 字段就是 dict 对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # object -> dict
    class Student:
    def __init__(self, id, name, age, sex, phone, email):
    self.id = id
    self.name = name
    self.age = age
    self.sex = sex
    self.phone = phone
    self.email = email

    stu = Student('007', '007', 28, 'male', '13000000000', '123@qq.com')
    print(type(stu)) # <class 'json_test.student.Student'>
    stu = stu.__dict__ # 将对象转成dict字典
    print(type(stu)) # <class 'dict'>
  • dict -> object

    __dict__ 赋值上 dict 即可


局部变量 vs 全局变量

注:在方法内部的变量是在=号前面的,那肯定是局部变量。如果是第一次出现在=号后面的,那肯定是调用的全局变量;全局变量可以在函数里面调用,局部变量只能在对应的函数里面调用,在该函数外面任何地方都无法被调用。


文件 LF 换行符 \n 和 CRLF \r\n 回车符

只要以 rb, wb (二进制) 模式读写, 就不会有替换的问题, 原来怎么样的文件就写成怎么样的文件, 不会有 diff


阿里云 sdk


Mac 平台 http 请求报证书错误

报错: Cannot connect to host ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')]

解决办法: 需要安装 Python 证书


单元测试

默认支持的是 unittest, 官网文档: https://docs.python.org/zh-cn/3/library/unittest.html

  • 测试命令: python3 -m unittest -v [py脚本].[测试类].[测试方法]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    $ python3 -m unittest -v test_async.Test_Async.test_subprocess
    test_subprocess (test_async.Test_Async) ...

    ------------------ test result ------------------
    ['git status' exited with 0]
    [stdout]
    On branch master
    Your branch is up to date with 'origin/master'.

    nothing to commit, working tree clean

    .
    ----------------------------------------------------------------------
    Ran 1 test in 0.103s

    OK
  • unittest 模块可以通过命令行运行模块、类和独立测试方法的测试:

    1
    2
    3
    python3 -m unittest -v test_module1 test_module2
    python3 -m unittest -v test_module.TestClass
    python3 -m unittest -v test_module.TestClass.test_method

vscode 中配置 单元测试

  1. 安装 测试框架. 只要第二部中配置测试框架, vscode 会自动提示安装.

  2. 配置 测试框架. 在 .vscode/settings.json 中配置

    测试框架有几个, nosetestsEnabled, pyTestEnabled, unittestEnabled, 这里使用 unittestEnabled, 其他的都必须设置为false,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    {
    "python.testing.autoTestDiscoverOnSaveEnabled": true, // 保存文件时自动发现测试用例
    "python.testing.nosetestsEnabled": false,
    "python.testing.pyTestEnabled": false,
    "python.testing.unittestEnabled": true,
    "python.testing.unittestArgs": [
    "-v",
    "-s",
    "./test_script/python",
    "-p",
    "test_*.py"
    ],
    "python.pythonPath": "D:\\Python36-32\\python.exe"
    }
  3. 代码中使用, 在 ./test_script/python 目录下新建一个 test_unittest.py 文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import unittest

    class Test_Dummy(unittest.TestCase):
    def setUp(self):
    print("--- setUp")

    def tearDown(self):
    print("--- tearDown")

    def test_hello(self):
    self.assertEqual(123, 123)
    print("--- hello")

    def test_world(self):
    print("--- world")
    1. vscode 中直接 点击 debug test, 输出日志在 debug console

    2. vscode 中直接 点击 run test. 输出日志在 output 中. (在 python test log 这个终端中.)


命令行执行单元测试

测试的可执行程序在 C:\Users\%USER%\AppData\Roaming\Python\Python36\Scripts\pytest.exe

常用的几个命令

1
2
3
4
5
6
pytest.exe test_mod.py   # run tests in module
pytest.exe somepath # run all tests below somepath
pytest.exe -q test_file_name.py # quite输出
pytest.exe -s test_file_name.py # -s 参数可以打印测试代码中的输出,默认不打印,print 没结果
pytest.exe test_mod.py::test_func # only run tests that match the "node ID",
pytest.exe test_mod.py::TestClass::test_method # run a single method in

输出测试结果到文件中

1
pytest.exe -s test_file_name.py --resultlog=report.txt

解决子目录 检测不到单元测试用例

./test_script/python 目下的子目录中也有单元测试用例, 但是 vscode 中却发现不了.

解决办法: 需要在 子目录中新建一个空文件 __init__.py, 然后点击一下 discover tests 即可

参考官网: https://code.visualstudio.com/docs/python/testing#_test-discovery


踩坑

ImportError: bad magic number in : b’\x03\xf3\r\n’

解决办法:删除项目中所有的 .pyc 文件。


断言 False 也通过

执行时警告: SyntaxWarning: assertion is always true, perhaps remove parentheses?

写法错误

1
2
3
assert (False, "--- wolegequ error") # 错误. 这里一定不能用括号括起来, 否者会被认为是一个 tuple, 判定为 True (通过断言)

assert False, "--- wolegequ error" # 正确.

参考: https://stackoverflow.com/questions/3112171/python-assert-with-and-without-parenthesis


运行pip报错:Fatal error in launcher: Unable to create process using ‘“‘

解决办法: 执行 pip 升级命令: python -m pip install --upgrade pip

参考: https://blog.csdn.net/cjeric/article/details/73518782


报错: MemoryError

可能的原因是使用 32 位的 Python 版本, 可以使用的虚拟内存只有 2g, 而实际使用的 (读文件) 超过 2g, 就会导致这个错误.

解决办法: 安装 64 位的 Python 版本


Mac pip 安装报错: Permission denied: /Library/Python/3.8

pip3 安装命令加上 --user 参数:

1
$ pip3 install package_name --user

参考: https://stackoverflow.com/questions/52949531/could-not-install-packages-due-to-an-environmenterror-errno-13


http 请求 10054 错误

报错: ('Connection aborted.', ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054, None))

解决办法: 在 headers 中加入代理信息, 模拟浏览器请求

1
2
3
4
5
6
7
8
9
10
11
headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"accept-encoding": "gzip, deflate, br",
"cache-control": "max-age=0",
"content-type": "application/x-www-form-urlencoded",
"dnt": "1",
"origin": "https://aavtrain.com",
"referer": "https://aavtrain.com/index.asp",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36",
}

参考:


RequestsDependencyWarning 异常

报了个警告: RequestsDependencyWarning

解决办法, 升级一下库即可

1
$ pip3 install --upgrade requests