# How to generate Pyc/pyo files # 1. Generate the import py_compile# parameter by writing code "def compile (file, Cfile=none, Dfile=none, Doraise=false, Optimize=-1): File: The source file to be compiled CFile: the compiled pyc file path and file name, by default directly after file plus C or O (will be saved in the current directory __pycache__ folder), PYO equivalent to the optimized PYC dfile: Replace the file displayed in the error message with Dfile Doraise:true or FALSE, if true, then a pycompileerror will be thrown if the files are compiled incorrectly. If False, compilation errors are displayed in Sys.stderr optimize: the level of optimization used for compilation, and the valid value is -1,0,1,2. -1 indicates that the current interpreter's optimization level is set using the command line if the optimization level is set by-O. Used to generate the Pyo file. Plainly, the last few parameters are basically less than "Py_compile.compile" ("Your_py_file") # 2. Generate # Python (-O)-M py_compile your_py_file.py with the command line, plus-O for optimization ' "Sometimes we don't want to just compile a py file, but instead compile all the py files under a folder." Python also provides us with a module ' import compileall# parameters as follows ' ' Def compile_dir (dir, maxlevels=10, Ddir=none, Force=false, Rx=none, Quiet=0, Legacy=false, Optimize=-1, Workers=1):d ir: Folder path maxlevels: Number of tiers of recursively compiled subdirectories, The default is to compile the 10-level subdirectory of the Py file into Pycddir: and the above dfile similar to force: If true, will be forced to compile to PYC, even if now PYC file is the latest, will still compile the Rx: a regular expression, you can exclude the directory you do not want to compile, Compile only the desired directory quiet: Give me a little bit of peace. After compiling, the information will not be printed in standard output. "' Compileall.compile_dir (" Your_dir ") # can also use command line # python-m Compileall Your_dir
let's compile a try.
first I define a function fuck in foo.py, and then compile it in bar.py, where the command line is not used and the effect is the same.
you will find a file in the __pycache__ directory in the current directory, which is just the bytecode file for the compiled code. We move it to the current directory and remove the foo.py and change the name, otherwise it cannot be imported .
The
discovery is still successful, and the Py file and the PYc file can be imported in the same way--------------------------------------------------------------------
How to generate a Pyc/pyo/pyd file