Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to avoid stale *.pyc files?

What's the best way to avoid stale *.pyc files? Sometimes, especially when switching branches in version control, some *.pyc files are left there and are used by Python instead of the source files I have.

What's the best strategy for making sure I don't create or unknowingly use stale *.pyc files?

like image 620
nicholaides Avatar asked Dec 24 '14 02:12

nicholaides


People also ask

How do I prevent PYC files?

Python can now be prevented from writing . pyc or . pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the sys.

Is it okay to delete .PYC files?

pyc files from a folder. You can use the find command (on OS X and Linux) to locate all of the . pyc files, and then use its delete option to delete them. Obviously, this can be used for any file type that you wish to eradicate, not just .

How do you not make a Pycache?

Suppressing the creation of __pycache__ When using the CPython interpreter (which is the original implementation of Python anyway), you can suppress the creation of this folder in two ways. Alternatively, you can set PYTHONDONTWRITEBYTECODE environment variable to any non-empty string.

How do I delete all my Pycache files?

Explains: First finds all __pycache__ folders in current directory. Execute rm -r {} + to delete each folder at step above ( {} signify for placeholder and + to end the command)


3 Answers

Similar to khampson, git and mercurial (and likely others) allow client side hooks. You can sprinkle around scripts that do

find -iname "*.pyc" -exec rm -f {} \; 

on linux at least. Search "git hooks" and "mercurial hooks" for more details.

like image 87
tdelaney Avatar answered Sep 29 '22 15:09

tdelaney


There is a useful environment variable for that: PYTHONDONTWRITEBYTECODE

export PYTHONDONTWRITEBYTECODE=true
like image 38
erthalion Avatar answered Sep 29 '22 15:09

erthalion


I would recommend a combined approach.

First, add *.pyc to your .gitignore file, which should help to avoid issues when switching branches (at least for cases where the cause is that a .pyc file somehow got committed). I generally always add both *.pyc and *.log to my .gitignore so as not to potentially commit any of those files accidentally, and so they don't clutter my git status output.

Second, create a wrapper shell script which first removes all .pyc files (recursively if your source directory structure calls for it) and then invokes your actual script. That should ensure any resulting .pyc files are newly created using the current source.

i.e. something like (without the & if you want the script to wait):

#!/bin.sh
rm -f *.pyc
./foo.py &
like image 44
khampson Avatar answered Sep 29 '22 15:09

khampson