Skip to content

Commit d9ca07a

Browse files
committed
Defer 5 more imports
- datetime - functools - io - subprocess - traceback
1 parent 53164e8 commit d9ca07a

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

cmd2/cmd2.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,12 @@
2626
import argparse
2727
import cmd
2828
import collections
29-
import datetime
30-
import functools
3129
import glob
32-
import io
33-
from io import StringIO
3430
import os
3531
import platform
3632
import re
3733
import shlex
38-
import subprocess
3934
import sys
40-
import traceback
4135
from typing import Callable, List, Optional, Union, Tuple
4236

4337
import pyperclip
@@ -133,6 +127,7 @@ def categorize(func: Union[Callable, Iterable], category: str) -> None:
133127

134128

135129
def _which(editor: str) -> Optional[str]:
130+
import subprocess
136131
try:
137132
editor_path = subprocess.check_output(['which', editor], stderr=subprocess.STDOUT).strip()
138133
editor_path = editor_path.decode()
@@ -170,6 +165,8 @@ def with_argument_list(func: Callable) -> Callable:
170165
method. Default passes a string of whatever the user typed.
171166
With this decorator, the decorated method will receive a list
172167
of arguments parsed from user input using shlex.split()."""
168+
import functools
169+
173170
@functools.wraps(func)
174171
def cmd_wrapper(self, cmdline):
175172
lexed_arglist = parse_quoted_string(cmdline)
@@ -186,6 +183,8 @@ def with_argparser_and_unknown_args(argparser: argparse.ArgumentParser) -> Calla
186183
:param argparser: argparse.ArgumentParser - given instance of ArgumentParser
187184
:return: function that gets passed parsed args and a list of unknown args
188185
"""
186+
import functools
187+
189188
# noinspection PyProtectedMember
190189
def arg_decorator(func: Callable):
191190
@functools.wraps(func)
@@ -226,6 +225,7 @@ def with_argparser(argparser: argparse.ArgumentParser) -> Callable:
226225
:param argparser: argparse.ArgumentParser - given instance of ArgumentParser
227226
:return: function that gets passed parsed args
228227
"""
228+
import functools
229229

230230
# noinspection PyProtectedMember
231231
def arg_decorator(func: Callable):
@@ -803,6 +803,7 @@ def perror(self, errmsg, exception_type=None, traceback_war=True):
803803
:return:
804804
"""
805805
if self.debug:
806+
import traceback
806807
traceback.print_exc()
807808

808809
if exception_type is None:
@@ -834,6 +835,7 @@ def ppaged(self, msg, end='\n'):
834835
:param msg: str - message to print to current stdout - anything convertible to a str with '{}'.format() is OK
835836
:param end: str - string appended after the end of the message if not already present, default a newline
836837
"""
838+
import subprocess
837839
if msg is not None and msg != '':
838840
try:
839841
msg_str = '{}'.format(msg)
@@ -1541,6 +1543,8 @@ def complete(self, text, state):
15411543
:param text: str - the current word that user is typing
15421544
:param state: int - non-negative integer
15431545
"""
1546+
import functools
1547+
15441548
if state == 0:
15451549
unclosed_quote = ''
15461550
self.set_completion_defaults()
@@ -1911,6 +1915,7 @@ def postparsing_postcmd(self, stop: bool) -> bool:
19111915
if not sys.platform.startswith('win'):
19121916
# Fix those annoying problems that occur with terminal programs like "less" when you pipe to them
19131917
if self.stdin.isatty():
1918+
import subprocess
19141919
proc = subprocess.Popen(shlex.split('stty sane'))
19151920
proc.communicate()
19161921
return stop
@@ -1935,6 +1940,7 @@ def onecmd_plus_hooks(self, line):
19351940
:param line: str - line of text read from input
19361941
:return: bool - True if cmdloop() should exit, False otherwise
19371942
"""
1943+
import datetime
19381944
stop = False
19391945
try:
19401946
statement = self._complete_statement(line)
@@ -2054,6 +2060,9 @@ def _redirect_output(self, statement):
20542060
20552061
:param statement: Statement - a parsed statement from the user
20562062
"""
2063+
import io
2064+
import subprocess
2065+
20572066
if statement.pipe_to:
20582067
self.kept_state = Statekeeper(self, ('stdout',))
20592068

@@ -2505,6 +2514,8 @@ def _help_menu(self, verbose=False):
25052514

25062515
def _print_topics(self, header, cmds, verbose):
25072516
"""Customized version of print_topics that can switch between verbose or traditional output"""
2517+
import io
2518+
25082519
if cmds:
25092520
if not verbose:
25102521
self.print_topics(header, cmds, 15, 80)
@@ -2539,7 +2550,7 @@ def _print_topics(self, header, cmds, verbose):
25392550
doc = getattr(self, self._func_named(command)).__doc__
25402551
else:
25412552
# we found the help function
2542-
result = StringIO()
2553+
result = io.StringIO()
25432554
# try to redirect system stdout
25442555
with redirect_stdout(result):
25452556
# save our internal stdout
@@ -2707,6 +2718,7 @@ def do_shell(self, command):
27072718
27082719
Usage: shell <command> [arguments]"""
27092720

2721+
import subprocess
27102722
try:
27112723
# Use non-POSIX parsing to keep the quotes around the tokens
27122724
tokens = shlex.split(command, posix=False)
@@ -2962,6 +2974,8 @@ def _generate_transcript(self, history, transcript_file):
29622974
"""Generate a transcript file from a given history of commands."""
29632975
# Save the current echo state, and turn it off. We inject commands into the
29642976
# output using a different mechanism
2977+
import io
2978+
29652979
saved_echo = self.echo
29662980
self.echo = False
29672981

0 commit comments

Comments
 (0)