python-1
一、搭建 Python 环境及简单使用
搭建python环境
python可以在多种操作系统环境中使用
• linux
大多linux发行版均默认安装了python环境。如果下载不同的,可到 www.python.org下载。软件安装方法参照linux软件安装。
输入python可启动python交互模式
程序编辑推荐使用vim
• windows
可下载安装python的msi包直接安装
自带python的GUI开发环境
开发工具很多
在linux下:
yum install *python*
安装完成后直接执行python命令进入python的交互模式
# python >>> >>> print 'hello word' hello word >>>exit() -----退出
文本模式(非交互模式)
简单编辑python程序
编写python脚本时可以直接用vim,脚本后缀名为.py
如: # touch hello.py # vim hello.py print "hello world"
执行脚本时
# python hello.py hello word
Python的文件类型
• 源代码
python源代码的文件以'python'为扩展名,由python程序解释,不需要编译;
• 字节代码
python源文件经编译后生成扩展名为"pyc"的文件
编译方法 import py_compile
py_compile.compile("hello.py)
• 优化代码
经过优化的源文件,扩展名为".pyo"
python -O -m py_compile hello.py
注:python文档是这样描述的:这个优化没有多大作用,只是移除了断言。 至于速度,运行几乎一样。
1.python脚本文件的标准写法
# vim hello.py #!/usr/bin/python print "hello world"
# chmod +x hello.py
# ./hello.py
2.编译python脚本(源代码编译后要比解释执行要快)
python很多功能通过模块完成,模块中会有很多方法可以直接使用
# vim com.py
import py_compile py_compile.compile('hello.py')
python com.py 执行后生成hello.pyc文件即编译后的文件
python hello.pyc 即可执行该文件
3.优化代码
python -O -m py_compile hello.py
python hello.pyo
浙公网安备 33010602011771号