Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile all py file to pyc file in a folder by writing a python script?

Tags:

python

I work on win system, and I wonder a way that I can use a python script which could run in cmd lines to mass compile the py files. I have write a simple python code.

import py_compile, os, glob
dir = 'D:\\FAS\\config'
for f in glob.glob(dir + '\\*.py'):
    py_compile.compile(f)
    print "Success compile the file:   %s" % f

It work inconveniently and can not compile the file in the folder's sub-folder. I hope your help.

like image 823
Jun HU Avatar asked Nov 22 '12 11:11

Jun HU


People also ask

How do you compile all files in Python?

Using compileall. compile_dir() function: It compiles every single python file present in the directory supplied. Using py_compile in Terminal: $ python -m py_compile File1.py File2.py File3.py ...


3 Answers

From the command line to compile all the files present in the current directory and in the subdirectory, you can simply use the following command.

python3 -m compileall . -q

remove -q if you want the list of compiled files.

You can stop recursion in subdirectories by using -l in

python3 -m compileall . -l

You can write script for that as well.

import compileall

compileall.compile_dir('D:/FAS/config', force=True)

Force will rebuild even if timestamps are up-to-date.

You can read more about it here

like image 99
Milind Patel Avatar answered Oct 19 '22 11:10

Milind Patel


import compileall

compileall.compile_dir('D:/FAS/config', force=True)
like image 30
Oleh Prypin Avatar answered Oct 19 '22 12:10

Oleh Prypin


I encountered similar issue when upgrading a library module. I had different module versions on different git branches and when I switch branch they stop working even if I recompiled using compileall.

My simple solution is to remove all .pyc files from the library and run the scripts so that it compiles all necessary modules itself. It worked!!

Easy command to remove the pyc files find libs/ -name *.pyc -exec rm {} \;

like image 1
Ravee Avatar answered Oct 19 '22 11:10

Ravee