Skip to content
This repository was archived by the owner on Oct 27, 2021. It is now read-only.

Commit 96e4b52

Browse files
committed
Converted Django scripts to argparse
Refs #19973.
1 parent 7018bcf commit 96e4b52

File tree

4 files changed

+59
-75
lines changed

4 files changed

+59
-75
lines changed

django/contrib/admin/bin/compress.py

+16-14
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,44 @@
11
#!/usr/bin/env python
2+
import argparse
23
import os
3-
import optparse
44
import subprocess
55
import sys
66

77
js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'admin', 'js')
88

99

1010
def main():
11-
usage = "usage: %prog [file1..fileN]"
1211
description = """With no file paths given this script will automatically
1312
compress all jQuery-based files of the admin app. Requires the Google Closure
1413
Compiler library and Java version 6 or later."""
15-
parser = optparse.OptionParser(usage, description=description)
16-
parser.add_option("-c", dest="compiler", default="~/bin/compiler.jar",
14+
parser = argparse.ArgumentParser(description=description)
15+
parser.add_argument('file', nargs='*')
16+
parser.add_argument("-c", dest="compiler", default="~/bin/compiler.jar",
1717
help="path to Closure Compiler jar file")
18-
parser.add_option("-v", "--verbose",
18+
parser.add_argument("-v", "--verbose",
1919
action="store_true", dest="verbose")
20-
parser.add_option("-q", "--quiet",
20+
parser.add_argument("-q", "--quiet",
2121
action="store_false", dest="verbose")
22-
(options, args) = parser.parse_args()
22+
options = parser.parse_args()
2323

2424
compiler = os.path.expanduser(options.compiler)
2525
if not os.path.exists(compiler):
2626
sys.exit("Google Closure compiler jar file %s not found. Please use the -c option to specify the path." % compiler)
2727

28-
if not args:
28+
if not options.file:
2929
if options.verbose:
3030
sys.stdout.write("No filenames given; defaulting to admin scripts\n")
31-
args = [os.path.join(js_path, f) for f in [
31+
files = [os.path.join(js_path, f) for f in [
3232
"actions.js", "collapse.js", "inlines.js", "prepopulate.js"]]
33+
else:
34+
files = options.file
3335

34-
for arg in args:
35-
if not arg.endswith(".js"):
36-
arg = arg + ".js"
37-
to_compress = os.path.expanduser(arg)
36+
for file_name in files:
37+
if not file_name.endswith(".js"):
38+
file_name = file_name + ".js"
39+
to_compress = os.path.expanduser(file_name)
3840
if os.path.exists(to_compress):
39-
to_compress_min = "%s.min.js" % "".join(arg.rsplit(".js"))
41+
to_compress_min = "%s.min.js" % "".join(file_name.rsplit(".js"))
4042
cmd = "java -jar %s --js %s --js_output_file %s" % (compiler, to_compress, to_compress_min)
4143
if options.verbose:
4244
sys.stdout.write("Running: %s\n" % cmd)

extras/csrf_migration_helper.py

+10-21
Original file line numberDiff line numberDiff line change
@@ -112,25 +112,15 @@
112112
# and fail to find real instances.
113113

114114

115+
from argparse import ArgumentParser
115116
import os
116117
import sys
117118
import re
118-
from optparse import OptionParser
119119

120-
USAGE = """
121-
This tool helps to locate forms that need CSRF tokens added and the
120+
DESCRIPTION = """This tool helps to locate forms that need CSRF tokens added and the
122121
corresponding view code. This processing is NOT fool proof, and you should read
123122
the help contained in the script itself. Also, this script may need configuring
124-
(by editing the script) before use.
125-
126-
Usage:
127-
128-
python csrf_migration_helper.py [--settings=path.to.your.settings] /path/to/python/code [more paths...]
129-
130-
Paths can be specified as relative paths.
131-
132-
With no arguments, this help is printed.
133-
"""
123+
(by editing the script) before use."""
134124

135125
_POST_FORM_RE = \
136126
re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
@@ -347,21 +337,20 @@ def main(pythonpaths):
347337
print("----")
348338

349339

350-
parser = OptionParser(usage=USAGE)
351-
parser.add_option("", "--settings", action="store", dest="settings", help="Dotted path to settings file")
352-
353340
if __name__ == '__main__':
354-
options, args = parser.parse_args()
355-
if len(args) == 0:
341+
parser = ArgumentParser(description=DESCRIPTION)
342+
parser.add_argument('files', nargs='*', help='Paths can be specified as relative paths.')
343+
parser.add_argument("--settings", help="Dotted path to settings file")
344+
options = parser.parse_args()
345+
if len(options.files) == 0:
356346
parser.print_help()
357347
sys.exit(1)
358348

359-
settings = getattr(options, 'settings', None)
360-
if settings is None:
349+
if options.settings is None:
361350
if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None:
362351
print("You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter")
363352
sys.exit(1)
364353
else:
365354
os.environ["DJANGO_SETTINGS_MODULE"] = settings
366355

367-
main(args)
356+
main(options.files)

scripts/manage_translations.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
#
1919
# $ python scripts/manage_translations.py lang_stats --language=es --resources=admin
2020

21+
from argparse import ArgumentParser
2122
import os
22-
from optparse import OptionParser
2323
from subprocess import call, Popen, PIPE
2424

2525
from django.core.management import call_command
@@ -167,18 +167,15 @@ def fetch(resources=None, languages=None):
167167
if __name__ == "__main__":
168168
RUNABLE_SCRIPTS = ('update_catalogs', 'lang_stats', 'fetch')
169169

170-
parser = OptionParser(usage="usage: %prog [options] cmd")
171-
parser.add_option("-r", "--resources", action='append',
170+
parser = ArgumentParser()
171+
parser.add_argument('cmd', nargs=1)
172+
parser.add_argument("-r", "--resources", action='append',
172173
help="limit operation to the specified resources")
173-
parser.add_option("-l", "--languages", action='append',
174+
parser.add_argument("-l", "--languages", action='append',
174175
help="limit operation to the specified languages")
175-
options, args = parser.parse_args()
176+
options = parser.parse_args()
176177

177-
if not args:
178-
parser.print_usage()
179-
exit(1)
180-
181-
if args[0] in RUNABLE_SCRIPTS:
182-
eval(args[0])(options.resources, options.languages)
178+
if options.cmd[0] in RUNABLE_SCRIPTS:
179+
eval(options.cmd[0])(options.resources, options.languages)
183180
else:
184181
print("Available commands are: %s" % ", ".join(RUNABLE_SCRIPTS))

tests/runtests.py

+25-29
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python
2+
from argparse import ArgumentParser
23
import logging
3-
from optparse import OptionParser
44
import os
55
import shutil
66
import subprocess
@@ -213,7 +213,7 @@ def django_tests(verbosity, interactive, failfast, test_labels):
213213

214214

215215
def bisect_tests(bisection_label, options, test_labels):
216-
state = setup(int(options.verbosity), test_labels)
216+
state = setup(options.verbosity, test_labels)
217217

218218
test_labels = test_labels or get_installed()
219219

@@ -271,7 +271,7 @@ def bisect_tests(bisection_label, options, test_labels):
271271

272272

273273
def paired_tests(paired_test, options, test_labels):
274-
state = setup(int(options.verbosity), test_labels)
274+
state = setup(options.verbosity, test_labels)
275275

276276
test_labels = test_labels or get_installed()
277277

@@ -307,43 +307,39 @@ def paired_tests(paired_test, options, test_labels):
307307

308308

309309
if __name__ == "__main__":
310-
usage = "%prog [options] [module module module ...]"
311-
parser = OptionParser(usage=usage)
312-
parser.add_option(
313-
'-v', '--verbosity', action='store', dest='verbosity', default='1',
314-
type='choice', choices=['0', '1', '2', '3'],
315-
help='Verbosity level; 0=minimal output, 1=normal output, 2=all '
316-
'output')
317-
parser.add_option(
310+
parser = ArgumentParser(description="Run the Django test suite.")
311+
parser.add_argument('modules', nargs='*', metavar='module',
312+
help='Optional path(s) to test modules; e.g. "i18n" or '
313+
'"i18n.tests.TranslationTests.test_lazy_objects".')
314+
parser.add_argument(
315+
'-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3],
316+
help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
317+
parser.add_argument(
318318
'--noinput', action='store_false', dest='interactive', default=True,
319319
help='Tells Django to NOT prompt the user for input of any kind.')
320-
parser.add_option(
320+
parser.add_argument(
321321
'--failfast', action='store_true', dest='failfast', default=False,
322322
help='Tells Django to stop running the test suite after first failed '
323323
'test.')
324-
parser.add_option(
324+
parser.add_argument(
325325
'--settings',
326326
help='Python path to settings module, e.g. "myproject.settings". If '
327-
'this isn\'t provided, the DJANGO_SETTINGS_MODULE environment '
328-
'variable will be used.')
329-
parser.add_option(
330-
'--bisect', action='store', dest='bisect', default=None,
327+
'this isn\'t provided, either the DJANGO_SETTINGS_MODULE '
328+
'environment variable or "test_sqlite" will be used.')
329+
parser.add_argument('--bisect',
331330
help='Bisect the test suite to discover a test that causes a test '
332331
'failure when combined with the named test.')
333-
parser.add_option(
334-
'--pair', action='store', dest='pair', default=None,
332+
parser.add_argument('--pair',
335333
help='Run the test suite in pairs with the named test to find problem '
336334
'pairs.')
337-
parser.add_option(
338-
'--liveserver', action='store', dest='liveserver', default=None,
335+
parser.add_argument('--liveserver',
339336
help='Overrides the default address where the live server (used with '
340337
'LiveServerTestCase) is expected to run from. The default value '
341338
'is localhost:8081.')
342-
parser.add_option(
343-
'--selenium', action='store_true', dest='selenium',
344-
default=False,
339+
parser.add_argument(
340+
'--selenium', action='store_true', dest='selenium', default=False,
345341
help='Run the Selenium tests as well (if Selenium is installed)')
346-
options, args = parser.parse_args()
342+
options = parser.parse_args()
347343
if options.settings:
348344
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
349345
else:
@@ -358,11 +354,11 @@ def paired_tests(paired_test, options, test_labels):
358354
os.environ['DJANGO_SELENIUM_TESTS'] = '1'
359355

360356
if options.bisect:
361-
bisect_tests(options.bisect, options, args)
357+
bisect_tests(options.bisect, options, options.modules)
362358
elif options.pair:
363-
paired_tests(options.pair, options, args)
359+
paired_tests(options.pair, options, options.modules)
364360
else:
365-
failures = django_tests(int(options.verbosity), options.interactive,
366-
options.failfast, args)
361+
failures = django_tests(options.verbosity, options.interactive,
362+
options.failfast, options.modules)
367363
if failures:
368364
sys.exit(bool(failures))

0 commit comments

Comments
 (0)