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?
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.
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 .
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.
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)
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.
There is a useful environment variable for that: PYTHONDONTWRITEBYTECODE
export PYTHONDONTWRITEBYTECODE=true
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 &
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With