trytete 发表于 2015-6-23 08:59:31

搭建Python环境与Python文件类型


[*]Linux环境
- 大多Linux发行版均默认安装了Python环境。
- 输入Python可启动Python交互模式
- 程序编辑推荐使用VIM

[*]Windows环境
- 可下载安装Python的msi包直接安装
- 自带Python的GUI开发环境
- 开发工具很多


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Linux交互界面
# python
Python 2.6.6 (r266:84292, Jan 22 2014, 09:37:14)
on linux2
Type "help", "copyright", "credits" or "license" for more information.
# 退出指令
>>>exit()
#
# 文本模式
# vim 1.py
print 'hello world'
# python 1.py
hello world
>>> print 'hello world'
hello world
>>> exit()
#





Python文件类型

[*]源代码


      - Python源代码的文件以“py”为扩展名,由Python程序解释,不需要编译

1
2
3
4
5
6
7
8
9
# vim 1.py
# python标准格式
#!/usr/bin/python
print 'hello world'
# chmod +x 1.py
# ls -l 1.py
-rwxr-xr-x 1 root root 39 6月21 08:59 1.py
# ./1.py
hello world





[*]字节代码
- Python源文件经编译后生产的扩展名为“pyc”的文件


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 引入模块,对1.py执行编译
# vim 2.py
import py_compile
py_compile.compile("1.py")
# 用python进行编译
# python 2.py
#
# 这里会生成一个以pyc结尾的文件
# ls -l
总用量 12
-rwxr-xr-x 1 root root39 6月21 08:59 1.py
-rw-r--r-- 1 root root 112 6月21 10:37 1.pyc
-rwxr-xr-x 1 root root46 6月21 10:37 2.py
# 这个文件也可以执行
# python 1.pyc
hello world





[*]优化代码
- 经过优化的源文件,扩展名为“pyo”


1
2
3
4
5
6
7
# python -O -m py_compile 1.py
# ls -l
总用量 16
-rwxr-xr-x 1 root root39 6月21 08:59 1.py
-rwxr-xr-x 1 root root 112 6月21 10:37 1.pyc
-rwxr-xr-x 1 root root 112 6月21 10:44 1.pyo
-rwxr-xr-x 1 root root46 6月21 10:37 2.py





三种代码执行效果

1
2
3
4
5
6
# python 1.py
hello world
# python 1.pyc
hello world
# python 1.pyo
hello world






页: [1]
查看完整版本: 搭建Python环境与Python文件类型