Skip to content

Commit

Permalink
FIX: Provide support for Python3. Local libdir=lib/python should now …
Browse files Browse the repository at this point in the history
…be usable for Python2 and Python3.
  • Loading branch information
jenisys committed Feb 16, 2016
1 parent 671d279 commit 31be0f9
Show file tree
Hide file tree
Showing 23 changed files with 55 additions and 47 deletions.
2 changes: 1 addition & 1 deletion README.rst
Expand Up @@ -40,7 +40,7 @@ all prerequisites::
pip install -r requirements.txt

Snapshots of the `behave`_ and `parse_type`_ implementations
are provided in the directory ``lib/python2/``. This directory is
are provided in the directory ``lib/python/``. This directory is
automatically used when you use ``bin/behave`` to run `behave`_.


Expand Down
5 changes: 0 additions & 5 deletions bin/behave_run.py
Expand Up @@ -11,7 +11,6 @@
# PROJECT-SPECIFIC SETUP PATHS:
# ----------------------------------------------------------------------------
import project_sitecustomize
from behave_ext.formatter import pretty2

# ----------------------------------------------------------------------------
# BEHAVE-PATCHES:
Expand All @@ -28,10 +27,6 @@ def monkeypatch_behave():
ansi_escapes2.AnsiColor.grey = ansi_escapes2.AnsiColor.white
ansi_escapes2.colors["grey"] = ansi_escapes.colors["white"]
AnsiStyle.parse_style = staticmethod(AnsiStyle.parse_style2)
# -- NOT-NEEDED-ANYMORE:
# from behave_ext.formatter import pretty2
# from behave.formatter._registry import register_as as format_register_as
# format_register_as("pretty", pretty2.SimplePrettyFormatter)

def setup_behave():
"""
Expand Down
3 changes: 2 additions & 1 deletion bin/project_sitecustomize.py
Expand Up @@ -18,10 +18,11 @@
# ----------------------------------------------------------------------------
# PROJECT-SPECIFIC PATHS:
# ----------------------------------------------------------------------------
# -- NOTE: lib/python should be usable for py2 and py3
py_version_major = sys.version_info[0]
HERE = os.path.dirname(__file__)
TOPA = os.path.abspath(os.path.join(HERE, ".."))
PYTHON_LIBDIR = os.path.join(TOPA, "lib", "python%s" % py_version_major)
PYTHON_LIBDIR = os.path.join(TOPA, "lib", "python")

def print_(text):
sys.stdout.write(text + "\n")
Expand Down
2 changes: 1 addition & 1 deletion features/steps/company_model.py
Expand Up @@ -45,7 +45,7 @@ def __init__(self):

def add_user(self, name, deparment):
assert name not in self.users
if not self.departments.has_key(deparment):
if deparment not in self.departments:
self.departments[deparment] = Department(deparment)
self.departments[deparment].add_member(name)

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Expand Up @@ -5,6 +5,7 @@
REQUIRES: py >= 1.4.17 (actually: py.io.terminalwriter)
"""

from __future__ import absolute_import
from py._io import terminalwriter
import os
import sys
Expand Down Expand Up @@ -56,7 +57,7 @@ def setup_style_descriptions(cls):
cls.setup_style_descriptions_from_environment()

# -- SETUP ARG-STYLE DESCRIPTIONS:
for style_name, description in cls.style_descriptions.items():
for style_name, description in list(cls.style_descriptions.items()):
if style_name.endswith("_arg"):
continue
arg_style_name = "{0}_arg".format(style_name)
Expand Down
File renamed without changes.
Expand Up @@ -3,11 +3,13 @@
Provides a PrettyFormatter that uses a terminal styles.
"""

from __future__ import absolute_import
from behave_ext.terminal import select_terminal_class, get_terminal_size
from behave_ext.__termwriter0 import StyledTerminalWriter
from behave.model_describe import ModelDescriptor
from behave.formatter.base import Formatter
from behave.textutil import indent, make_indentation
import six


class ModelPrinter(object):
Expand Down Expand Up @@ -78,7 +80,7 @@ def print_feature_head(self, feature):
text = u"%s%s: %s" % (indentation, feature.keyword, feature.name)
self.writer.write(text, style="feature")
if self.show_source:
text = self.location_text(unicode(feature.location), 2)
text = self.location_text(six.text_type(feature.location), 2)
self.writer.write(text, style="comments")
self.writer.write("\n")
indentation = self.indentations[self.INDENT_FEATURE_DESCRIPTION]
Expand All @@ -101,7 +103,7 @@ def print_statement_head(self, statement, steps=None):
if self.show_source:
assert self.show_location
indent_size = self.location_indentations.pop(0)
location = unicode(statement.location)
location = six.text_type(statement.location)
text = self.location_text(location, indent_size)
self.writer.write(text, style="comments")
self.writer.write("\n")
Expand Down Expand Up @@ -136,7 +138,7 @@ def print_step_with_status(self, step, status, match=None,
location = ""
if match:
arguments = match.arguments
location = unicode(match.location)
location = six.text_type(match.location)

style = status
arg_style = "%s_arg" % style
Expand All @@ -147,7 +149,7 @@ def print_step_with_status(self, step, status, match=None,
self.writer.write(step.keyword + ' ', style=style)
line_length = 1 + len(indentation) + len(step.keyword)

step_name = unicode(step.name)
step_name = six.text_type(step.name)
text_start = 0
for arg in arguments:
if arg.end <= text_start:
Expand All @@ -171,7 +173,7 @@ def print_step_with_status(self, step, status, match=None,

if self.show_source:
if self.show_timings and status in ('passed', 'failed'):
assert isinstance(location, unicode)
assert isinstance(location, six.text_type)
location += " in %0.3fs" % step.duration
text = self.location_text(location, location_indentsize)
self.writer.write(text, style="comments")
Expand Down Expand Up @@ -211,7 +213,7 @@ def print_docstring(self, docstring):
self.step_lines += self.calculate_terminal_lines(text)

def print_exception(self, exception):
exception_text = unicode(exception, encoding="utf-8")
exception_text = six.text_type(exception, encoding="utf-8")
self.writer.write(exception_text + "\n", style="failed")
self.writer.flush()

Expand Down
File renamed without changes.
Expand Up @@ -12,6 +12,8 @@
* http://en.wikipedia.org/wiki/ANSI_escape_code
"""

from __future__ import absolute_import
from six.moves import range
class AnsiColor(object):
"""ANSI foreground color codes."""
black = 30
Expand Down
Expand Up @@ -5,6 +5,7 @@
REQUIRES: colorama >= 0.2.7
"""

from __future__ import absolute_import
from .ansiterm import AnsiTerminalWriter
import sys

Expand Down
Expand Up @@ -3,6 +3,7 @@
This module provides a terminal with ANSI escape sequence support.
"""

from __future__ import absolute_import
from . import ansi_escapes, baseterm, style
import logging
import os
Expand Down
Expand Up @@ -4,6 +4,7 @@
matching terminal for your platform or operating system.
"""

from __future__ import absolute_import
import sys


Expand Down
Expand Up @@ -3,6 +3,7 @@
This module describes terminal/text styles in a platform independent way.
"""

from __future__ import absolute_import
import os
import sys

Expand Down Expand Up @@ -73,7 +74,7 @@ def update_from_environment(self):

def update_arg_styles(self, stylesheet, override=True):
# -- SETUP ARG-STYLE DESCRIPTIONS:
for style_name, style_description in stylesheet.items():
for style_name, style_description in list(stylesheet.items()):
if ( style_name.endswith("_arg") or
(style_name not in self.styles_with_arg)):
continue
Expand Down
Expand Up @@ -5,6 +5,7 @@
Provides low-level Win32 API for Windows terminal output.
"""

from __future__ import absolute_import
from ctypes import Structure, c_short as short, c_ushort as ushort
import sys

Expand Down
Expand Up @@ -4,9 +4,11 @@
matching terminal for your platform or operating system.
"""

from __future__ import absolute_import
from . import baseterm, style, win32
from ctypes import byref
import os
import six

__all__ = [ "WindowsStyle", "Terminal" ]

Expand Down Expand Up @@ -73,7 +75,7 @@ def reset_style(self):
self.__set_text_attribute(self._default_attribute)

def set_color(self, color):
if isinstance(color, basestring):
if isinstance(color, six.string_types):
color_value = getattr(win32.WinColor, color, None)
if color_value is None:
raise AttributeError("unknown color='%s'" % color)
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
60 changes: 30 additions & 30 deletions lib/python2/pysite.py → lib/python/pysite.py
Expand Up @@ -59,10 +59,12 @@
"""

from __future__ import absolute_import, print_function
import sys
import os
import __builtin__
import six.moves.builtins
import traceback
from six.moves import range, input

# Prefixes for site-packages; add additional prefixes like /usr/local here
PREFIXES = [sys.prefix, sys.exec_prefix]
Expand Down Expand Up @@ -162,20 +164,20 @@ def addpackage(sitedir, name, known_paths):
continue
try:
if line.startswith(("import ", "import\t")):
exec line
exec(line)
continue
line = line.rstrip()
dir, dircase = makepath(sitedir, line)
if not dircase in known_paths and os.path.exists(dir):
sys.path.append(dir)
known_paths.add(dircase)
except Exception as err:
print >>sys.stderr, "Error processing line {:d} of {}:\n".format(
n+1, fullname)
print("Error processing line {:d} of {}:\n".format(
n+1, fullname), file=sys.stderr)
for record in traceback.format_exception(*sys.exc_info()):
for line in record.splitlines():
print >>sys.stderr, ' '+line
print >>sys.stderr, "\nRemainder of file ignored"
print(' '+line, file=sys.stderr)
print("\nRemainder of file ignored", file=sys.stderr)
break
if reset:
known_paths = None
Expand Down Expand Up @@ -371,8 +373,8 @@ def __call__(self, code=None):
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
six.moves.builtins.quit = Quitter('quit')
six.moves.builtins.exit = Quitter('exit')


class _Printer(object):
Expand All @@ -396,7 +398,7 @@ def __setup(self):
for filename in self.__files:
filename = os.path.join(dir, filename)
try:
fp = file(filename, "rU")
fp = open(filename, "rU")
data = fp.read()
fp.close()
break
Expand All @@ -423,32 +425,32 @@ def __call__(self):
while 1:
try:
for i in range(lineno, lineno + self.MAXLINES):
print self.__lines[i]
print(self.__lines[i])
except IndexError:
break
else:
lineno += self.MAXLINES
key = None
while key is None:
key = raw_input(prompt)
key = input(prompt)
if key not in ('', 'q'):
key = None
if key == 'q':
break

def setcopyright():
"""Set 'copyright' and 'credits' in __builtin__"""
__builtin__.copyright = _Printer("copyright", sys.copyright)
six.moves.builtins.copyright = _Printer("copyright", sys.copyright)
if sys.platform[:4] == 'java':
__builtin__.credits = _Printer(
six.moves.builtins.credits = _Printer(
"credits",
"Jython is maintained by the Jython developers (www.jython.org).")
else:
__builtin__.credits = _Printer("credits", """\
six.moves.builtins.credits = _Printer("credits", """\
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.""")
here = os.path.dirname(os.__file__)
__builtin__.license = _Printer(
six.moves.builtins.license = _Printer(
"license", "See http://www.python.org/%.3s/license.html" % sys.version,
["LICENSE.txt", "LICENSE"],
[os.path.join(here, os.pardir), here, os.curdir])
Expand All @@ -468,7 +470,7 @@ def __call__(self, *args, **kwds):
return pydoc.help(*args, **kwds)

def sethelper():
__builtin__.help = _Helper()
six.moves.builtins.help = _Helper()

def aliasmbcs():
"""On Windows, some default encodings are not provided by Python,
Expand Down Expand Up @@ -515,8 +517,7 @@ def execsitecustomize():
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print >>sys.stderr, \
"'import sitecustomize' failed; use -v for traceback"
print("'import sitecustomize' failed; use -v for traceback", file=sys.stderr)


def execusercustomize():
Expand All @@ -529,8 +530,7 @@ def execusercustomize():
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print>>sys.stderr, \
"'import usercustomize' failed; use -v for traceback"
print("'import usercustomize' failed; use -v for traceback", file=sys.stderr)


def main():
Expand Down Expand Up @@ -580,15 +580,15 @@ def _script():
"""
args = sys.argv[1:]
if not args:
print "sys.path = ["
print("sys.path = [")
for dir in sys.path:
print " %r," % (dir,)
print "]"
print "USER_BASE: %r (%s)" % (USER_BASE,
"exists" if os.path.isdir(USER_BASE) else "doesn't exist")
print "USER_SITE: %r (%s)" % (USER_SITE,
"exists" if os.path.isdir(USER_SITE) else "doesn't exist")
print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE
print(" %r," % (dir,))
print("]")
print("USER_BASE: %r (%s)" % (USER_BASE,
"exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
print("USER_SITE: %r (%s)" % (USER_SITE,
"exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
sys.exit(0)

buffer = []
Expand All @@ -598,7 +598,7 @@ def _script():
buffer.append(USER_SITE)

if buffer:
print os.pathsep.join(buffer)
print(os.pathsep.join(buffer))
if ENABLE_USER_SITE:
sys.exit(0)
elif ENABLE_USER_SITE is False:
Expand All @@ -609,7 +609,7 @@ def _script():
sys.exit(3)
else:
import textwrap
print textwrap.dedent(help % (sys.argv[0], os.pathsep))
print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
sys.exit(10)

if __name__ == '__main__':
Expand Down
Empty file.

0 comments on commit 31be0f9

Please sign in to comment.