summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xREADME.md3
-rwxr-xr-xcmd2.py127
-rwxr-xr-xexamples/alias_startup.py2
-rwxr-xr-xexamples/arg_print.py2
-rwxr-xr-xexamples/argparse_example.py2
-rwxr-xr-xexamples/environment.py2
-rwxr-xr-xexamples/event_loops.py2
-rwxr-xr-xexamples/example.py2
-rwxr-xr-xexamples/help_categories.py2
-rwxr-xr-xexamples/paged_output.py2
-rwxr-xr-xexamples/persistent_history.py2
-rwxr-xr-xexamples/pirate.py2
-rwxr-xr-xexamples/python_scripting.py2
-rwxr-xr-xexamples/remove_unused.py2
-rwxr-xr-xexamples/subcommands.py2
-rwxr-xr-xexamples/submenus.py2
-rwxr-xr-xexamples/tab_completion.py2
-rwxr-xr-xexamples/table_display.py2
-rwxr-xr-xsetup.py4
-rw-r--r--tests/test_cmd2.py38
-rw-r--r--tests/test_parsing.py5
-rw-r--r--tests/test_transcript.py11
22 files changed, 56 insertions, 164 deletions
diff --git a/README.md b/README.md
index b68dba47..ee57246b 100755
--- a/README.md
+++ b/README.md
@@ -57,8 +57,7 @@ pip install -U cmd2
```
cmd2 works with Python 3.4+ on Windows, macOS, and Linux. It is pure Python code with
-the only 3rd-party dependencies being on [six](https://pypi.python.org/pypi/six),
-[pyparsing](http://pyparsing.wikispaces.com), and [pyperclip](https://github.com/asweigart/pyperclip).
+the only 3rd-party dependencies being on [pyparsing](http://pyparsing.wikispaces.com), and [pyperclip](https://github.com/asweigart/pyperclip).
Windows has an additional dependency on [pyreadline](https://pypi.python.org/pypi/pyreadline). Non-Windows platforms
have an additional dependency on [wcwidth](https://pypi.python.org/pypi/wcwidth). Finally, Python
3.4 has an additional dependency on [contextlib2](https://pypi.python.org/pypi/contextlib2).
diff --git a/cmd2.py b/cmd2.py
index 057f95f1..b1021a28 100755
--- a/cmd2.py
+++ b/cmd2.py
@@ -32,12 +32,13 @@ import datetime
import functools
import glob
import io
+from io import StringIO
import os
import platform
import re
import shlex
import signal
-import six
+import subprocess
import sys
import tempfile
import traceback
@@ -51,17 +52,15 @@ except ImportError:
import pyparsing
import pyperclip
+from pyperclip import PyperclipException
+import six.moves as sm # Used for sm.input
# Collection is a container that is sizable and iterable
# It was introduced in Python 3.6. We will try to import it, otherwise use our implementation
try:
from collections.abc import Collection, Iterable
except ImportError:
-
- if six.PY3:
- from collections.abc import Sized, Iterable, Container
- else:
- from collections import Sized, Iterable, Container
+ from collections.abc import Sized, Iterable, Container
# noinspection PyAbstractClass
class Collection(Sized, Iterable, Container):
@@ -78,44 +77,12 @@ except ImportError:
return True
return NotImplemented
-# Newer versions of pyperclip are released as a single file, but older versions had a more complicated structure
-try:
- from pyperclip.exceptions import PyperclipException
-except ImportError:
- # noinspection PyUnresolvedReferences
- from pyperclip import PyperclipException
-
-# next(it) gets next item of iterator it. This is a replacement for calling it.next() in Python 2 and next(it) in Py3
-from six import next
-
-# Possible types for text data. This is basestring() in Python 2 and str in Python 3.
-from six import string_types
-
-# Used for sm.input: raw_input() for Python 2 or input() for Python 3
-import six.moves as sm
-
-# itertools.zip() for Python 2 or zip() for Python 3 - produces an iterator in both cases
-from six.moves import zip
-
-# If using Python 2.7, try to use the subprocess32 package backported from Python 3.2 due to various improvements
-# NOTE: The feature to pipe output to a shell command won't work correctly in Python 2.7 without this
-try:
- # noinspection PyPackageRequirements
- import subprocess32 as subprocess
-except ImportError:
- import subprocess
-
-# Python 3.4 and earlier require contextlib2 for temporarily redirecting stderr and stdout
+# Python 3.4 require contextlib2 for temporarily redirecting stderr and stdout
if sys.version_info < (3, 5):
from contextlib2 import redirect_stdout, redirect_stderr
else:
from contextlib import redirect_stdout, redirect_stderr
-if six.PY3:
- from io import StringIO # Python3
-else:
- from io import BytesIO as StringIO # Python2
-
# Detect whether IPython is installed to determine if the built-in "ipy" command should be included
ipython_available = True
try:
@@ -136,14 +103,12 @@ except ImportError:
except ImportError:
pass
-
# Check what implementation of readline we are using
class RlType(Enum):
GNU = 1
PYREADLINE = 2
NONE = 3
-
rl_type = RlType.NONE
if 'pyreadline' in sys.modules:
@@ -167,25 +132,6 @@ elif 'gnureadline' in sys.modules or 'readline' in sys.modules:
rl_basic_quote_characters = ctypes.c_char_p.in_dll(readline_lib, "rl_basic_quote_characters")
orig_rl_basic_quote_characters_addr = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
-
-# BrokenPipeError and FileNotFoundError exist only in Python 3. Use IOError for Python 2.
-if six.PY3:
- BROKEN_PIPE_ERROR = BrokenPipeError
- FILE_NOT_FOUND_ERROR = FileNotFoundError
-else:
- BROKEN_PIPE_ERROR = FILE_NOT_FOUND_ERROR = IOError
-
-# On some systems, pyperclip will import gtk for its clipboard functionality.
-# The following code is a workaround for gtk interfering with printing from a background
-# thread while the CLI thread is blocking in raw_input() in Python 2 on Linux.
-if six.PY2 and sys.platform.startswith('lin'):
- try:
- # noinspection PyUnresolvedReferences
- import gtk
- gtk.set_interactive(0)
- except ImportError:
- pass
-
__version__ = '0.9.0'
# Pyparsing enablePackrat() can greatly speed up parsing, but problems have been seen in Python 3 in the past
@@ -250,8 +196,7 @@ def set_strip_quotes(val):
def _which(editor):
try:
editor_path = subprocess.check_output(['which', editor], stderr=subprocess.STDOUT).strip()
- if six.PY3:
- editor_path = editor_path.decode()
+ editor_path = editor_path.decode()
except subprocess.CalledProcessError:
editor_path = None
return editor_path
@@ -431,12 +376,6 @@ def get_paste_buffer():
:return: str - contents of the clipboard
"""
pb_str = pyperclip.paste()
-
- # If value returned from the clipboard is unicode and this is Python 2, convert to a "normal" Python 2 string first
- if six.PY2 and not isinstance(pb_str, str):
- import unicodedata
- pb_str = unicodedata.normalize('NFKD', pb_str).encode('ascii', 'ignore')
-
return pb_str
@@ -659,7 +598,7 @@ class AddSubmenu(object):
if self.persistent_history_file:
try:
readline.read_history_file(self.persistent_history_file)
- except FILE_NOT_FOUND_ERROR:
+ except FileNotFoundError:
pass
try:
@@ -843,12 +782,12 @@ class Cmd(cmd.Cmd):
readline.read_history_file(persistent_history_file)
# default history len is -1 (infinite), which may grow unruly
readline.set_history_length(persistent_history_length)
- except FILE_NOT_FOUND_ERROR:
+ except FileNotFoundError:
pass
atexit.register(readline.write_history_file, persistent_history_file)
- # Call super class constructor. Need to do it in this way for Python 2 and 3 compatibility
- cmd.Cmd.__init__(self, completekey=completekey, stdin=stdin, stdout=stdout)
+ # Call super class constructor
+ super().__init__(completekey=completekey, stdin=stdin, stdout=stdout)
# Commands to exclude from the help menu and tab completion
self.hidden_commands = ['eof', 'eos', '_relative_load']
@@ -974,7 +913,7 @@ class Cmd(cmd.Cmd):
self.stdout.write(msg_str)
if not msg_str.endswith(end):
self.stdout.write(end)
- except BROKEN_PIPE_ERROR:
+ except BrokenPipeError:
# This occurs if a command's output is being piped to another process and that process closes before the
# command is finished. If you would like your application to print a warning message, then set the
# broken_pipe_warning attribute to the message you want printed.
@@ -1066,7 +1005,7 @@ class Cmd(cmd.Cmd):
self.pipe_proc = None
else:
self.stdout.write(msg_str)
- except BROKEN_PIPE_ERROR:
+ except BrokenPipeError:
# This occurs if a command's output is being piped to another process and that process closes before the
# command is finished. If you would like your application to print a warning message, then set the
# broken_pipe_warning attribute to the message you want printed.
@@ -1708,12 +1647,8 @@ class Cmd(cmd.Cmd):
# We will use readline's display function (rl_display_match_list()), so we
# need to encode our string as bytes to place in a C array.
- if six.PY3:
- encoded_substitution = bytes(substitution, encoding='utf-8')
- encoded_matches = [bytes(cur_match, encoding='utf-8') for cur_match in matches_to_display]
- else:
- encoded_substitution = bytes(substitution)
- encoded_matches = [bytes(cur_match) for cur_match in matches_to_display]
+ encoded_substitution = bytes(substitution, encoding='utf-8')
+ encoded_matches = [bytes(cur_match, encoding='utf-8') for cur_match in matches_to_display]
# rl_display_match_list() expects matches to be in argv format where
# substitution is the first element, followed by the matches, and then a NULL.
@@ -2300,19 +2235,12 @@ class Cmd(cmd.Cmd):
# Create a pipe with read and write sides
read_fd, write_fd = os.pipe()
- # Make sure that self.poutput() expects unicode strings in Python 3 and byte strings in Python 2
- write_mode = 'w'
- read_mode = 'r'
- if six.PY2:
- write_mode = 'wb'
- read_mode = 'rb'
-
# Open each side of the pipe and set stdout accordingly
# noinspection PyTypeChecker
- self.stdout = io.open(write_fd, write_mode)
+ self.stdout = io.open(write_fd, 'w')
self.redirecting = True
# noinspection PyTypeChecker
- subproc_stdin = io.open(read_fd, read_mode)
+ subproc_stdin = io.open(read_fd, 'r')
# We want Popen to raise an exception if it fails to open the process. Thus we don't set shell to True.
try:
@@ -2359,7 +2287,7 @@ class Cmd(cmd.Cmd):
try:
# Close the file or pipe that stdout was redirected to
self.stdout.close()
- except BROKEN_PIPE_ERROR:
+ except BrokenPipeError:
pass
finally:
# Restore self.stdout
@@ -2584,9 +2512,8 @@ class Cmd(cmd.Cmd):
elif rl_type == RlType.PYREADLINE:
readline.rl.mode._display_completions = orig_pyreadline_display
- # Need to set empty list this way because Python 2 doesn't support the clear() method on lists
- self.cmdqueue = []
- self._script_dir = []
+ self.cmdqueue.clear()
+ self._script_dir.clear()
return stop
@@ -2857,11 +2784,11 @@ Usage: Usage: unalias [-a] name [name ...]
that the return value can differ from
the text advertised to the user """
local_opts = opts
- if isinstance(opts, string_types):
+ if isinstance(opts, str):
local_opts = list(zip(opts.split(), opts.split()))
fulloptions = []
for opt in local_opts:
- if isinstance(opt, string_types):
+ if isinstance(opt, str):
fulloptions.append((opt, opt))
else:
try:
@@ -3422,10 +3349,8 @@ Script should contain one command per line, just like command would be typed in
try:
# Read all lines of the script and insert into the head of the
# command queue. Add an "end of script (eos)" command to cleanup the
- # self._script_dir list when done. Specify file encoding in Python
- # 3, but Python 2 doesn't allow that argument to open().
- kwargs = {'encoding': 'utf-8'} if six.PY3 else {}
- with open(expanded_path, **kwargs) as target:
+ # self._script_dir list when done.
+ with open(expanded_path, encoding='utf-8') as target:
self.cmdqueue = target.read().splitlines() + ['eos'] + self.cmdqueue
except IOError as e:
self.perror('Problem accessing script from {}:\n{}'.format(expanded_path, e))
@@ -4129,10 +4054,6 @@ class CmdResult(namedtuple_with_two_defaults('CmdResult', ['out', 'err', 'war'])
"""If err is an empty string, treat the result as a success; otherwise treat it as a failure."""
return not self.err
- def __nonzero__(self):
- """Python 2 uses this method for determining Truthiness"""
- return self.__bool__()
-
if __name__ == '__main__':
# If run as the main application, simply start a bare-bones cmd2 application with only built-in functionality.
diff --git a/examples/alias_startup.py b/examples/alias_startup.py
index 23e51048..30764c27 100755
--- a/examples/alias_startup.py
+++ b/examples/alias_startup.py
@@ -16,7 +16,7 @@ class AliasAndStartup(cmd2.Cmd):
""" Example cmd2 application where we create commands that just print the arguments they are called with."""
def __init__(self):
- cmd2.Cmd.__init__(self, startup_script='.cmd2rc')
+ super().__init__(startup_script='.cmd2rc')
if __name__ == '__main__':
diff --git a/examples/arg_print.py b/examples/arg_print.py
index 3083c0d7..18fa483f 100755
--- a/examples/arg_print.py
+++ b/examples/arg_print.py
@@ -28,7 +28,7 @@ class ArgumentAndOptionPrinter(cmd2.Cmd):
self.shortcuts.update({'$': 'aprint', '%': 'oprint'})
# Make sure to call this super class __init__ *after* setting commentGrammars and/or updating shortcuts
- cmd2.Cmd.__init__(self)
+ super().__init__()
# NOTE: It is critical that the super class __init__ method be called AFTER updating certain parameters which
# are not settable at runtime. This includes the commentGrammars, shortcuts, multilineCommands, etc.
diff --git a/examples/argparse_example.py b/examples/argparse_example.py
index ca2173e7..e9b377ba 100755
--- a/examples/argparse_example.py
+++ b/examples/argparse_example.py
@@ -28,7 +28,7 @@ class CmdLineApp(Cmd):
self.settable['maxrepeats'] = 'Max number of `--repeat`s allowed'
# Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell
- Cmd.__init__(self, use_ipython=False, transcript_files=transcript_files)
+ super().__init__(use_ipython=False, transcript_files=transcript_files)
# Disable cmd's usage of command-line arguments as commands to be run at invocation
# self.allow_cli_args = False
diff --git a/examples/environment.py b/examples/environment.py
index ca39711e..c245f55d 100755
--- a/examples/environment.py
+++ b/examples/environment.py
@@ -16,7 +16,7 @@ class EnvironmentApp(Cmd):
def __init__(self):
self.settable.update({'degrees_c': 'Temperature in Celsius'})
self.settable.update({'sunny': 'Is it sunny outside?'})
- Cmd.__init__(self)
+ super().__init__()
def do_sunbathe(self, arg):
if self.degrees_c < 20:
diff --git a/examples/event_loops.py b/examples/event_loops.py
index 24efa830..53d3ca2b 100755
--- a/examples/event_loops.py
+++ b/examples/event_loops.py
@@ -12,7 +12,7 @@ import cmd2
class Cmd2EventBased(cmd2.Cmd):
"""Basic example of how to run cmd2 without it controlling the main loop."""
def __init__(self):
- cmd2.Cmd.__init__(self)
+ super().__init__()
# ... your class code here ...
diff --git a/examples/example.py b/examples/example.py
index 94ca7693..612d81e5 100755
--- a/examples/example.py
+++ b/examples/example.py
@@ -35,7 +35,7 @@ class CmdLineApp(Cmd):
self.shortcuts.update({'&': 'speak'})
# Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell
- Cmd.__init__(self, use_ipython=False)
+ super().__init__(use_ipython=False)
speak_parser = argparse.ArgumentParser()
speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
diff --git a/examples/help_categories.py b/examples/help_categories.py
index e7e3373d..cfb5f253 100755
--- a/examples/help_categories.py
+++ b/examples/help_categories.py
@@ -18,7 +18,7 @@ class HelpCategories(Cmd):
def __init__(self):
# Set use_ipython to True to enable the "ipy" command which embeds and interactive IPython shell
- Cmd.__init__(self, use_ipython=False)
+ super().__init__(use_ipython=False)
def do_connect(self, _):
"""Connect command"""
diff --git a/examples/paged_output.py b/examples/paged_output.py
index cb213087..bb410af6 100755
--- a/examples/paged_output.py
+++ b/examples/paged_output.py
@@ -11,7 +11,7 @@ class PagedOutput(cmd2.Cmd):
""" Example cmd2 application where we create commands that just print the arguments they are called with."""
def __init__(self):
- cmd2.Cmd.__init__(self)
+ super().__init__()
@with_argument_list
def do_page_file(self, args):
diff --git a/examples/persistent_history.py b/examples/persistent_history.py
index e1874212..61e26b9c 100755
--- a/examples/persistent_history.py
+++ b/examples/persistent_history.py
@@ -15,7 +15,7 @@ class Cmd2PersistentHistory(cmd2.Cmd):
:param hist_file: file to load readline history from at start and write it to at end
"""
- cmd2.Cmd.__init__(self, persistent_history_file=hist_file, persistent_history_length=500)
+ super().__init__(persistent_history_file=hist_file, persistent_history_length=500)
self.allow_cli_args = False
self.prompt = 'ph> '
diff --git a/examples/pirate.py b/examples/pirate.py
index f3a8fc7a..7fe3884b 100755
--- a/examples/pirate.py
+++ b/examples/pirate.py
@@ -23,7 +23,7 @@ class Pirate(Cmd):
self.shortcuts.update({'~': 'sing'})
"""Initialize the base class as well as this one"""
- Cmd.__init__(self)
+ super().__init__()
# prompts and defaults
self.gold = 0
self.initial_gold = self.gold
diff --git a/examples/python_scripting.py b/examples/python_scripting.py
index 5f7996e2..7e2cf345 100755
--- a/examples/python_scripting.py
+++ b/examples/python_scripting.py
@@ -25,7 +25,7 @@ class CmdLineApp(cmd2.Cmd):
def __init__(self):
# Enable the optional ipy command if IPython is installed by setting use_ipython=True
- cmd2.Cmd.__init__(self, use_ipython=True)
+ super().__init__(use_ipython=True)
self._set_prompt()
self.intro = 'Happy 𝛑 Day. Note the full Unicode support: 😇 (Python 3 only) đŸ’©'
diff --git a/examples/remove_unused.py b/examples/remove_unused.py
index cf26fcff..8a567123 100755
--- a/examples/remove_unused.py
+++ b/examples/remove_unused.py
@@ -16,7 +16,7 @@ class RemoveUnusedBuiltinCommands(cmd2.Cmd):
""" Example cmd2 application where we remove some unused built-in commands."""
def __init__(self):
- cmd2.Cmd.__init__(self)
+ super().__init__()
# To hide commands from displaying in the help menu, add them to the hidden_commands list
self.hidden_commands.append('py')
diff --git a/examples/subcommands.py b/examples/subcommands.py
index cbe4f634..031b17b2 100755
--- a/examples/subcommands.py
+++ b/examples/subcommands.py
@@ -20,7 +20,7 @@ class SubcommandsExample(cmd2.Cmd):
"""
def __init__(self):
- cmd2.Cmd.__init__(self)
+ super().__init__()
# subcommand functions for the base command
def base_foo(self, args):
diff --git a/examples/submenus.py b/examples/submenus.py
index 1e3da0da..44b17f33 100755
--- a/examples/submenus.py
+++ b/examples/submenus.py
@@ -19,7 +19,7 @@ class ThirdLevel(cmd2.Cmd):
"""To be used as a third level command class. """
def __init__(self, *args, **kwargs):
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
self.prompt = '3rdLevel '
self.top_level_attr = None
self.second_level_attr = None
diff --git a/examples/tab_completion.py b/examples/tab_completion.py
index 1419b294..919e9560 100755
--- a/examples/tab_completion.py
+++ b/examples/tab_completion.py
@@ -16,7 +16,7 @@ class TabCompleteExample(cmd2.Cmd):
""" Example cmd2 application where we a base command which has a couple subcommands."""
def __init__(self):
- cmd2.Cmd.__init__(self)
+ super().__init__()
add_item_parser = argparse.ArgumentParser()
add_item_group = add_item_parser.add_mutually_exclusive_group()
diff --git a/examples/table_display.py b/examples/table_display.py
index 68b73d0f..2e6ea804 100755
--- a/examples/table_display.py
+++ b/examples/table_display.py
@@ -37,7 +37,7 @@ class TableDisplay(cmd2.Cmd):
"""Example cmd2 application showing how you can display tabular data."""
def __init__(self):
- cmd2.Cmd.__init__(self)
+ super().__init__()
def ptable(self, tabular_data, headers=()):
"""Format tabular data for pretty-printing as a fixed-width table and then display it using a pager.
diff --git a/setup.py b/setup.py
index 2c74899a..c231e7ea 100755
--- a/setup.py
+++ b/setup.py
@@ -61,7 +61,7 @@ Programming Language :: Python :: Implementation :: PyPy3
Topic :: Software Development :: Libraries :: Python Modules
""".splitlines())))
-INSTALL_REQUIRES = ['pyparsing >= 2.1.0', 'pyperclip >= 1.6.0', 'six']
+INSTALL_REQUIRES = ['pyparsing >= 2.1.0', 'pyperclip >= 1.6.0']
EXTRAS_REQUIRE = {
# Windows also requires pyreadline to ensure tab completion works
@@ -82,7 +82,7 @@ if int(setuptools.__version__.split('.')[0]) < 18:
INSTALL_REQUIRES.append('contextlib2')
TESTS_REQUIRE = ['pytest', 'pytest-xdist']
-DOCS_REQUIRE = ['sphinx', 'sphinx_rtd_theme', 'pyparsing', 'pyperclip', 'six']
+DOCS_REQUIRE = ['sphinx', 'sphinx_rtd_theme', 'pyparsing', 'pyperclip', 'wcwidth']
setup(
name="cmd2",
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index 04498c49..9f0b13ee 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -145,10 +145,7 @@ now: True
def test_base_shell(base_app, monkeypatch):
m = mock.Mock()
- subprocess = 'subprocess'
- if six.PY2:
- subprocess = 'subprocess32'
- monkeypatch.setattr("{}.Popen".format(subprocess), m)
+ monkeypatch.setattr("{}.Popen".format('subprocess'), m)
out = run_cmd(base_app, 'shell echo a')
assert out == []
assert m.called
@@ -642,15 +639,8 @@ def test_pipe_to_shell_error(base_app, capsys):
# Try to pipe command output to a shell command that doesn't exist in order to produce an error
run_cmd(base_app, 'help | foobarbaz.this_does_not_exist')
out, err = capsys.readouterr()
-
assert not out
-
expected_error = 'FileNotFoundError'
- if six.PY2:
- if sys.platform.startswith('win'):
- expected_error = 'WindowsError'
- else:
- expected_error = 'OSError'
assert err.startswith("EXCEPTION of type '{}' occurred with message:".format(expected_error))
@@ -719,8 +709,8 @@ def test_base_colorize(base_app):
def _expected_no_editor_error():
expected_exception = 'OSError'
- # If using Python 2 or PyPy (either 2 or 3), expect a different exception than with Python 3
- if six.PY2 or hasattr(sys, "pypy_translation_info"):
+ # If PyPy, expect a different exception than with Python 3
+ if hasattr(sys, "pypy_translation_info"):
expected_exception = 'EnvironmentError'
expected_text = normalize("""
@@ -885,8 +875,7 @@ def test_cmdloop_without_rawinput():
class HookFailureApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
def postparsing_precmd(self, statement):
"""Simulate precmd hook failure."""
@@ -910,8 +899,7 @@ def test_precmd_hook_failure(hook_failure):
class SayApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
def do_say(self, arg):
self.poutput(arg)
@@ -953,8 +941,7 @@ def test_interrupt_noquit(say_app):
class ShellApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
self.default_to_shell = True
@pytest.fixture
@@ -1020,8 +1007,7 @@ def test_ansi_prompt_escaped():
class HelpApp(cmd2.Cmd):
"""Class for testing custom help_* methods which override docstring help."""
def __init__(self, *args, **kwargs):
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
def do_squat(self, arg):
"""This docstring help will never be shown because the help_squat method overrides it."""
@@ -1077,8 +1063,7 @@ def test_help_overridden_method(help_app):
class HelpCategoriesApp(cmd2.Cmd):
"""Class for testing custom help_* methods which override docstring help."""
def __init__(self, *args, **kwargs):
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
@cmd2.with_category('Some Category')
def do_diddly(self, arg):
@@ -1342,9 +1327,7 @@ def test_which_editor_bad():
class MultilineApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
self.multilineCommands = ['orate']
-
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
orate_parser = argparse.ArgumentParser()
orate_parser.add_argument('-s', '--shout', action="store_true", help="N00B EMULATION MODE")
@@ -1395,8 +1378,7 @@ def test_clipboard_failure(capsys):
class CmdResultApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- cmd2.Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
def do_affirmative(self, arg):
self._last_result = cmd2.CmdResult(arg)
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index ba5126f6..e2367a37 100644
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -299,22 +299,18 @@ def test_parse_multiline_ignores_terminators_in_comments(parser):
assert results.terminator[0] == '\n'
assert results.terminator[1] == '\n'
-# Unicode support is only present in cmd2 for Python 3
-@pytest.mark.skipif(sys.version_info < (3,0), reason="cmd2 unicode support requires python3")
def test_parse_command_with_unicode_args(parser):
line = 'drink café'
results = parser.parseString(line)
assert results.command == 'drink'
assert results.args == 'café'
-@pytest.mark.skipif(sys.version_info < (3, 0), reason="cmd2 unicode support requires python3")
def test_parse_unicode_command(parser):
line = 'café au lait'
results = parser.parseString(line)
assert results.command == 'café'
assert results.args == 'au lait'
-@pytest.mark.skipif(sys.version_info < (3,0), reason="cmd2 unicode support requires python3")
def test_parse_redirect_to_unicode_filename(parser):
line = 'dir home > café'
results = parser.parseString(line)
@@ -323,7 +319,6 @@ def test_parse_redirect_to_unicode_filename(parser):
assert results.output == '>'
assert results.outputTo == 'café'
-@pytest.mark.skipif(sys.version_info < (3,0), reason="cmd2 unicode support requires python3")
def test_parse_input_redirect_from_unicode_filename(input_parser):
line = '< café'
results = input_parser.parseString(line)
diff --git a/tests/test_transcript.py b/tests/test_transcript.py
index a579b04a..311a3f42 100644
--- a/tests/test_transcript.py
+++ b/tests/test_transcript.py
@@ -33,8 +33,7 @@ class CmdLineApp(Cmd):
# Add stuff to settable and/or shortcuts before calling base class initializer
self.settable['maxrepeats'] = 'Max number of `--repeat`s allowed'
- # Need to use this older form of invoking super class constructor to support Python 2.x and Python 3.x
- Cmd.__init__(self, *args, **kwargs)
+ super().__init__(*args, **kwargs)
self.intro = 'This is an intro banner ...'
# Configure how arguments are parsed for commands using decorators
@@ -267,12 +266,8 @@ def test_transcript(request, capsys, filename, feedback_to_output):
expected_start = ".\n----------------------------------------------------------------------\nRan 1 test in"
expected_end = "s\n\nOK\n"
out, err = capsys.readouterr()
- if six.PY3:
- assert err.startswith(expected_start)
- assert err.endswith(expected_end)
- else:
- assert err == ''
- assert out == ''
+ assert err.startswith(expected_start)
+ assert err.endswith(expected_end)
@pytest.mark.parametrize('expected, transformed', [