1.文档化字符串例子
#!/bin/env python
def getHtml():
"getHtml function is use get html infomation"
print 'getHtml() do ...'
getHtml()
help(getHtml)
2.if __name__=='__main__': 作用
使用该办法的py文件可单独作为其他模块使用,也可单独执行使用,以test.py文件为例
#!/bin/env python
#math.py
def getHtml():
"getHtml function is use get html infomation"
print 'getHtml() do ...'
# getHtml()
# help(getHtml)
def test():
print -2 * 4 + 3 ** 2
def square(x):
return x * x
if __name__=='__main__':
test()
getHtml()
#!/usr/env python
#test.py
import math
print math.square(3)
执行情况:
[root@localhost ch1]# python test.py
9
[root@localhost ch1]# python math.py
1
getHtml() do ...
[root@localhost ch1]#
3.pyc/pyo/pyd
什么是pyc文件
pyc是一种二进制文件,是由py文件经过编译后,生成的文件,是一种byte code,py文件变成pyc文件后,加载的速度有所提高,而且pyc是一种跨平台的字节码,是由python的虚拟机来执行的,这个是类似于JAVA或者.NET的虚拟机的概念。pyc的内容,是跟python的版本相关的,不同版本编译后的pyc文件是不同的,2.5编译的pyc文件,2.4版本的 python是无法执行的。
例子:
[root@localhost ch1]# python -m py_compile math.py
[root@localhost ch1]# ls -lrt
-rwxrwxrwx. 1 root root 291 Oct 10 23:11 math.py
-rwxrwxrwx. 1 root root 550 Oct 10 23:14 math.pyc
[root@localhost ch1]# file math.py
math.py: a /bin/env python\015 script text executable
[root@localhost ch1]# file math.pyc
math.pyc: python 2.6 byte-compiled
[root@localhost ch1]#
什么是pyo文件
pyo是优化编译后的程序 python -O 源文件即可将源程序编译为pyo文件
例子:
什么是pyd文件
pyd是python的动态链接库。
4.python批量编译
#!/usr/env python
#build.py
import compileall
compileall.compile_dir(r'/mnt/hgfs/share/ch1/')
执行结果:
[root@localhost ch1]# ls -lrt
total 6
-rwxrwxrwx. 1 root root 66 Oct 10 22:54 test.py
-rwxrwxrwx. 1 root root 291 Oct 10 23:11 math.py
-rwxrwxrwx. 1 root root 100 Oct 10 23:23 build.py
-rwxrwxrwx. 1 root root 203 Oct 10 23:23 build.pyc
-rwxrwxrwx. 1 root root 630 Oct 10 23:23 math.pyc
-rwxrwxrwx. 1 root root 172 Oct 10 23:23 test.pyc