Python3--实例技巧

概述

最近项目中需要弃用Makefile,用python作为编译框架。在这里记录一些技巧类实践

入门语法:Python 教程

实践技巧

基础

开启http server(web)

进入到html目录下, 目录下面有index.html
python3 -m http.server 8000
打开http://$hostip:8000即可访问

维测

  • 让脚本报错后立即进入调试模式:执行时带上-i参数
  • 查看如何使用内置模块:python -m pydoc -p xxx

字典<-->json

Python3 JSON 数据解析 | 菜鸟教程

判断变量是否存在

查看模块内容

help() 和 dir()

>>> dir(os)
...
rs', 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']
>>> dir(os.umask)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>>

语法检查

  • flake8
  • PyFlakes
  • pycodestyle
  • Pylint

格式化

  • black

utf-8

必须放在首行或者第二行

-*- coding:utf-8 -*-

关闭生成pyc

  1. 带参执行
python3 -B test.py
  1. 环境变量中设置以下参数:
export PYTHONDONTWRITEBYTECODE=1
  1. 在python中设置参数
import sys
sys.dont_write_bytecode = True

调试类

printf打印技巧

  • 打印重复字符
Python 3.6.9 (default, Jan 26 2021, 15:33:00)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(">"*10)
>>>>>>>>>>
>>> print("="*10)
==========
>>>
  • 格式化输出
    使用占位符{} 替代 %s,%d
>>> a = 1
>>> b = "work"
>>> c = [1, "a", "b"]
>>> d = {"name": "xiaoming", "weight": 180 }
>>> print("test {}".format(a))
test 1
>>> print("test {}".format(b))
test work
>>> print("test {}".format(c))
test [1, 'a', 'b']
>>> print("test {}".format(d))
test {'name': 'xiaoming', 'weight': 180}
>>>

数据结构类

二进制或者数据流处理

使用struct模块,可以实现类似c语言中的结构体操作
详见:Python3--struct模块

创建子进程

接口调用

装饰器

动态调用

  • 动态执行,类似函数指针:
    1. eval(action)(); action是函数名称
    2. getattr:获取属性
posted @ 2021-12-03 23:52  whilewell  阅读(66)  评论(0编辑  收藏  举报