Generate a single PYC file
Python is a good thing, it provides a built-in class library to implement the Py file compiled into a PYC file, this module is the py_compile module.
The use of the method is very simple, as shown below, directly in the idle, you can compile a py file into a pyc file. (assuming a Windows environment)
Import Py_compile
Py_compile.compile (R ' h:/game/test.py ')
Compile function Prototypes:
Compile (file[, cfile[, dfile[, Doraise]])
File indicates the path of the py file that needs to be compiled
The CFile represents the compiled PYC file name and path, which by default is a byte code that adds C or o,o directly after the file file name
Dfile This parameter English can not understand, please greatly enlighten us. (Despise oneself) Original: It is used as the name of the source file in error messages instead offile
Doraise can be two values, true or FALSE, if true, a pycompileerror is thrown, or if there is an error in compiling the file, there will be a bug that appears by default in Sys.stderr without throwing an exception
(from python2.5 documentation)
Batch Build PYC files
Generally speaking, our project is in a directory, generally do not say just compile a py file, but need to be the entire folder of the py file compiled into a pyc file, and Python for us to provide another module: Compileall. Here's how to use it:
Import Compileall
Compileall. Compile_dir (R ' h:/game ')
This compiles the game directory and the py file under its subdirectory into a PYC file. Hey, it's easy enough. Take a look at the description of the compile_dir function:
Compile_dir (dir[, maxlevels[, ddir[, force[, rx[, Quiet]] []]
Dir indicates the folder location that needs to be compiled
Maxlevels represents the number of levels of subdirectories that need to be compiled recursively, which by default is 10 layers, that is, by default, the PY files in the 10-tier subdirectory are compiled into PYC
Ddir English does not understand, the original: it is used as the base path from which the filenames used in error messages would be generated.
If force is true, it will be forced to compile to PYC, even if the current PYc file is up to date, it will be forced to compile once, the PYc file contains a timestamp, and the Python compiler will decide, depending on the time, whether the PYc file needs to be regenerated once
Rx represents a regular expression, such as the ability to exclude unwanted directories, or only those that are eligible for compilation
Quiet if true, the information is not printed in standard output after compilation.
Code snippet:
#-*-Coding=utf-8
‘‘‘
#编译目录下所有py文件为 PYc File
Import Compileall
Compileall.compile_dir (r "D:\python") #r "D:\python" path
‘‘‘
#编译 a single py file to PYc file
Import Py_compile
Py_compile.compile (r "d:\python\test.py") # r "d:\python\test.py": Path
Python py to become a PYC file