python 入门 (一)

本文介绍了Python语言的三种运行方式:直接解释执行、通过文件执行及赋予文件执行权限直接运行。此外,还探讨了Python的编译过程,包括如何将Python源文件编译为.pyc和.pyo文件,以及这些编译文件的作用。

输出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/archive/2013/06/01/3112517.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值