1. 使用方式
- 解释器交互方式
----python shell
----ipython - 建立程序文件
----文件执行
示例:
在CentOS7.5下
vim /tmp/hello.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
print 'Hello world!'
保存后执行
python /tmp/hello.py
或者
chmod u+x /tmp/hello.py
cd /tmp
./hello.py
2. 文件类型
- 源代码
- 字节代码
- 优化代码
源代码文件
python源代码文件以“.py”为扩展名,由python程序解释,不需要编译。
示例:
vim /tmp/1.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
print "It is said that Python is easy.?"
保存后执行
python /tmp/1.py
字节代码文件
python源码文件经编译后生成的扩展名为"pyc"的文件。
编译方法(插入py_compile模块):
import py_compile
py_compile.compile('py文件路径')
示例:
vim /tmp/2.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import py_compile
py_compile.compile('/tmp/1.py')
保存后执行
python /tmp/2.py
在/tmp目录下将会出现1.pyc文件,此时若移动,改名或者删除源码文件,仍然可以正常执行1.pyc文件。
[root@localhost tmp]# python 1.pyc
It is said that Python is easy.?
[root@localhost tmp]# file 1.pyc
1.pyc: python 2.7 byte-compiled
优化代码
经过优化的源码文件,扩展名为“pyo”
生成方式:
python -O -m py_compile 1.py
示例:
备注:执行.pyc或者.pyo文件,不需要源码文件存在,因为已经将源码文件内容编译后存到了二进制文件。