简体   繁体   中英

How to force Django every time recreate .pyc files?

I start using Django in PyCharm recently with git. Sometimes I have problem with running the server it shows some errors which I fixed. In order to solve this problem I should every time manually remove .pyc files. And run server again. How I can force it two override .pyc files every time when I compile my source? Thank you for your answers.

Thanks for @jbat100 and @Leonardo.Z. I figured it out. I pass PYTHONDONTWRITEBYTECODE=1. And it work as a magic. However sadly I can just accept only one answer I hope @jbat100 will not be angry with me.

Since Python 2.6 Python can 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.dont_write_bytecode variable , and Python code can change the value to modify the interpreter's behaviour. via: Interpreter Changes

Leonardo's anwer is probably what you're looking for but you can also just remove the .pyc files with the shell

find . -name "*.pyc" -exec rm -rf {} \;

There's a Django snippet also to do that

import os
directory = os.listdir('.')
for filename in directory:
    if filename[-3:] == 'pyc':
        print '- ' + filename
        os.remove(filename)

You can also check out the compileall utility which is used to compile python sources and has options to force recompilation.

I use the following code to achieve that:

import subprocess
subprocess.call('find . -name "*.py[co]" -delete', shell=True)

To use it as a manage.py command , you can do the following.

Place this code in: <app_name>/management/commands/delete_pyc.py

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):    
    help = """Delete all .pyc/.pyo files"""    
    def handle(self, *args, **options):
        import subprocess
        subprocess.call('find . -name "*.py[co]" -delete', shell=True)

To run do:

python manage.py delete_pyc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM