python 入门 (一)

输出hello world 

[root@chenchun py]# python
Python 2.6.6 (r266:84292, Sep 11 2012, 08:28:27) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world';
hello world

或者 创建文件执行 输出

[root@chenchun py]# vim hello.py
# 在 hello.py 文件中 输入
print 'hello world'
[root@chenchun py]# python hello.py
hello world

或者在文件hello.py 第一行加上

#!/usr/bin/python
print 'hello world'

然后给程序加上可执行权限

[root@chenchun py]# chmod +x hello.py

这样就可以直接运行,无需使用python命令

[root@chenchun py]# ./hello.py 
hello world

python 是解释型, 也是编译型。上面说的是解释型运行,接下来看下python如何编译。

# 创建 compile.py 
[root@chenchun py]# vim compile.py 
#!/usr/bin/python
import  py_compile

py_compile.compile('hello.py')

# 导包加使用编译函数来编译。
# 运行后,看可以看到多了一个hello.pyc的文件
[root@chenchun py]# ./compile.py 
[root@chenchun py]# ls
compile.py  hello.py  hello.pyc

# 然后运行 
[root@chenchun py]# python hello.pyc 
hello world
# 第二种 命令行编译

[root@chenchun py]# python -O -m py_compile hello.py
[root@chenchun py]# ls
compile.py  hello.py  hello.pyc  hello.pyo
[root@chenchun py]# python hello.pyo 
hello world

pyc是由py文件经过编译后生成的二进制文件,py文件变成pyc文件后,加载的速度有所提高,并且可以实现源码隐藏。
pyo是优化编译后的程序,也可以提高加载速度,针对嵌入式系统,把需要的模块编译成pyo文件可以减少容量。

原文地址:https://www.cnblogs.com/pangou/p/3112517.html