写出多平台的Python代码

Presenter Notes

自我介绍

陈剑 @knownsec

Presenter Notes

插播广告---->knownsec招聘

感谢Python

Presenter Notes

提供良好的多平台基础

  • POSIX标准

先补刀

  • 依赖解释器
  • 内存消耗大
  • 无法直接利用多核CPU
  • Python 2/3
  • 部分内置模块 (特定依赖)
  • 图形化库 (没有统一)
  • 如何分发应用 (没有统一)

Presenter Notes

  • 相对与C/C++
  • 解释器需要考虑使用哪种Jython,IronPython
  • 内存不贵~
  • GIL 全局解释器锁, 微线程,多线程分化

硬编码

  • 写死基础目录
  • 目录拼接方式 (os.sep)
  • 创建临时文件(tempfile)
  • 文件名编码
  • 文件内容硬编码(换行,内容编码)
  • 使用os.system

Presenter Notes

依赖导入

  • 了解内置模块兼容性
  • 第三方组件选型
  • 其他语言扩展的模块
  • 优先使用绝对导入
  • 拆分模块,通过标准的API调用(组件化)

Presenter Notes

系统特性

  • POSIX / UNIX
  • 异步IO (select, epoll, kqueue, IOCP)
  • 配置管理 (sysctl / 注册表)
  • 权限管理
  • 网络外围
  • 硬件与驱动

Presenter Notes

包分发方式

  • distutile (setup.py, pip)
  • py2exe (2008年就停止维护)
  • pyinstaller
  • apt-get
  • yum
  • ports
  • ...

Presenter Notes

一些好的实践

  • 了解各个系统间差异 (阅读文档)
  • 阅读PEP规范
  • 避免使用os.system/subprocess
  • 以低权限运行 (隔离)
  • 使用virtualenv (隔离)
  • 使用logging/warnings
  • 自动化测试

Presenter Notes

篇幅有限

GitHub https://github.com/cj1324/multi-platform-python-tips

Presenter Notes

Q & A

Presenter Notes

谢谢大家

Presenter Notes