如何编译Python程序生成.pyc文件

Python/PHP/Perl 开发与设计
回复
头像
ubuntu-mm
帖子: 54
注册时间: 2010-02-28 12:26
来自: 武汉
送出感谢: 0
接收感谢: 3 次
联系:

如何编译Python程序生成.pyc文件

#1

帖子 ubuntu-mm » 2011-06-18 11:00

Howto Generate a .pyc From Compiling a Python Program

In this post, I'll give you an example to demonstrates how to generate a .pyc from compiling a python program.
在本帖中,我将用一个实例演示如何编译Python程序生成.pyc文件。


What is the .pyc? A .pyc file is a compiled python bytecode file, you can visit how do I create a pyc file [1]for more information.
什么是.pyc文件? .pyc文件也就是一个已编译的python 字节码文件,您可以通过访问 how do I create a pyc file 一文获取更多信息。

Fist, I write a python script named hello.py as following:
首先,编写一个python脚本并命名为hello.py,如下所示:

#!/usr/bin/python
#
# File: hello.py
# Date: June 16 th , 2011
# Author: mutse < yyhoo2.young@gmail.com >
#
print “Hello, welcome to python world!”

Then use chmod command to change its file privilege.
接下来,使用chmod命令修改文件权限。

$ chmod a+x hello.py

Now, edit a python script as pycoder.py.
现在,编辑一个名为pycoder.py的python脚本.

#!/usr/bin/python
#
# File: pycoder.py
# Date: June 16 th , 2011
# Author: mutse < yyhoo2.young@gmail.com >
#
import py_compile

file = raw_input("Enter Your File Name: ")
py_compile.compile(file)
print ".pyc of the python script " + file + " is generated."

Then, do the same thing as hello.py.
接下来,做修改hello.py文件权限的同样的工作(修改pycoder.py文件权限)。

$ chmod a+x pycoder.py

At last, please run pycoder.py script, and a pyc bytecode hello.pyc is generated.
最后,请运行pycoder.py脚本,生成 hello.pyc 字节码文件。

$ ./pycoder.py
Enter Your File Name: hello.py
.pyc of the python script hello.py is generated.
Be With Freedom, Be With Ubuntu!
与自由同在,与Ubuntu同行!

欢迎访问默之的博客:http://mutse.github.com
回复

回到 “Python/Php/Perl”