Python3--实例技巧
概述
最近项目中需要弃用Makefile,用python作为编译框架。在这里记录一些技巧类实践
入门语法:Python 教程
实践技巧
基础
字典<-->json
Python3 JSON 数据解析 | 菜鸟教程
判断变量是否存在
- python判断变量是否存在
- python判断对象是否存在 - 如何检查变量是否存在? | 推荐
查看模块内容
>>> 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
utf-8
-*- coding:utf-8 -*-
关闭生成pyc
- 带参执行
python3 -B test.py
- 环境变量中设置以下参数:
export PYTHONDONTWRITEBYTECODE=1
调试类
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模块