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
判断变量是否存在
查看模块内容
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
- 带参执行
python3 -B test.py
- 环境变量中设置以下参数:
export PYTHONDONTWRITEBYTECODE=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模块
创建子进程
接口调用
装饰器
- Python小技巧:装饰器(Decorator)_哔哩哔哩_bilibili
需要关注:装饰器(wrapper()),函数体,出参(ret),入参(*args) - 7.10 让你的装饰器写得更轻松的神库 — Python黑魔法手册 1.0.0 documentation | decorator
动态调用
- 动态执行,类似函数指针:
eval(action)()
; action是函数名称- getattr:获取属性
本文来自博客园,作者:whilewell,转载请注明原文链接:https://www.cnblogs.com/viiv/p/15640641.html