File: clean_pyc.py

package info (click to toggle)
python-django-extensions 4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,820 kB
  • sloc: python: 18,601; javascript: 7,354; makefile: 108; xml: 17
file content (55 lines) | stat: -rw-r--r-- 1,671 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- coding: utf-8 -*-
import fnmatch
import os
from os.path import join as _j
from typing import List

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

from django_extensions.management.utils import signalcommand


class Command(BaseCommand):
    help = "Removes all python bytecode compiled files from the project."

    requires_system_checks: List[str] = []

    def add_arguments(self, parser):
        parser.add_argument(
            "--optimize",
            "-o",
            "-O",
            action="store_true",
            dest="optimize",
            default=False,
            help="Remove optimized python bytecode files",
        )
        parser.add_argument(
            "--path",
            "-p",
            action="store",
            dest="path",
            help="Specify path to recurse into",
        )

    @signalcommand
    def handle(self, *args, **options):
        project_root = options.get("path", getattr(settings, "BASE_DIR", None))
        if not project_root:
            project_root = getattr(settings, "BASE_DIR", None)

        verbosity = options["verbosity"]
        if not project_root:
            raise CommandError(
                "No --path specified and settings.py does not contain BASE_DIR"
            )

        exts = options["optimize"] and "*.py[co]" or "*.pyc"

        for root, dirs, filenames in os.walk(project_root):
            for filename in fnmatch.filter(filenames, exts):
                full_path = _j(root, filename)
                if verbosity > 1:
                    self.stdout.write("%s\n" % full_path)
                os.remove(full_path)