changeset 107:450aff4c97e3

py35 compat
author Jeff Hammel <k0scist@gmail.com>
date Fri, 31 Mar 2017 17:06:59 -0700
parents 1f84c6def8bd
children 1a8a977e7d5d
files decoupage/cli.py decoupage/create_index.py decoupage/factory.py decoupage/formatters.py decoupage/index.py decoupage/web.py tox.ini
diffstat 7 files changed, 47 insertions(+), 22 deletions(-) [+]
line wrap: on
line diff
--- a/decoupage/cli.py	Fri Mar 31 16:38:02 2017 -0700
+++ b/decoupage/cli.py	Fri Mar 31 17:06:59 2017 -0700
@@ -19,6 +19,7 @@
 
 here = os.path.dirname(os.path.realpath(__file__))
 
+
 class DecoupageServer(Decoupage):
     """serve locally with decoupage"""
     # TODO: deprecate; move Decoupage to a few classes
@@ -81,17 +82,18 @@
     # TODO: allow choice amongst server classes
     printable_address = '127.0.0.1' if options.address == '0.0.0.0' else options.address
     server = simple_server.make_server(options.address, options.port, app)
-    print 'serving directory %s ( %s ) at \nhttp://%s:%d/' % (directory,
-                                                              'file://' + directory, # XXX
-                                                              printable_address,
-                                                              options.port)
+    print("""serving directory {directory} ( file://{directory} ) at
+http://{hostname}:{port}/'""".format(directory=directory,
+                                     hostname=printable_address,
+                                     port=options.port))
+
     if options.print_ip:
         # from http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
         hostname = "google.com"
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         s.connect((hostname,80))
         hostname = s.getsockname()[0]
-        print "http://%s:%s/" % (hostname, options.port)
+        print ("http://{hostname}:{port}/".format(hostname=hostname, port=options.port))
         s.close()
 
     # serve directory contents via decoupage
@@ -100,5 +102,6 @@
     except KeyboardInterrupt:
         pass
 
+
 if __name__ == '__main__':
     main()
--- a/decoupage/create_index.py	Fri Mar 31 16:38:02 2017 -0700
+++ b/decoupage/create_index.py	Fri Mar 31 17:06:59 2017 -0700
@@ -39,7 +39,7 @@
                         help="directory to create index for (current working directory by default)")
     options = parser.parse_args(args)
 
-    print CreateIndex(options.directory)
+    print(CreateIndex(options.directory))
 
 
 if __name__ == '__main__':
--- a/decoupage/factory.py	Fri Mar 31 16:38:02 2017 -0700
+++ b/decoupage/factory.py	Fri Mar 31 17:06:59 2017 -0700
@@ -1,11 +1,11 @@
-from web import Decoupage
+from .web import Decoupage
 from paste.httpexceptions import HTTPExceptionHandler
 
 def namespace_conf(keystr, app_conf):
     keystr += '.'
     return dict([(key.split(keystr, 1)[-1], value)
                  for key, value in app_conf.items()
-                 if key.startswith(keystr) ])        
+                 if key.startswith(keystr) ])
 
 
 def factory(global_conf, **app_conf):
@@ -13,4 +13,3 @@
     app_conf = namespace_conf('decoupage', app_conf)
     app = Decoupage(**app_conf)
     return HTTPExceptionHandler(app)
-    
--- a/decoupage/formatters.py	Fri Mar 31 16:38:02 2017 -0700
+++ b/decoupage/formatters.py	Fri Mar 31 17:06:59 2017 -0700
@@ -341,9 +341,17 @@
         formatters[entry_point.name] = formatter
     return formatters
 
+
 def main(args=sys.argv[1:]):
+    """CLI"""
+
     for name, formatter in formatters().items():
-        print '%s%s' % (name, formatter.__doc__ and ': ' + formatter.__doc__ or '')
+        description = ''
+        if formatter.__doc__:
+            description = ': {}'.format(formatter.__doc__)
+        print ('{name}{description}'.format(name=name,
+                                            description=description))
+
 
 if __name__ == '__main__':
     main()
--- a/decoupage/index.py	Fri Mar 31 16:38:02 2017 -0700
+++ b/decoupage/index.py	Fri Mar 31 17:06:59 2017 -0700
@@ -7,19 +7,25 @@
 
 import argparse
 import os
-import subprocess
 import sys
 
 here = os.path.dirname(os.path.realpath(__file__))
-string = (str, unicode)
 
 def index(directory):
+    """
+    returns string representation of directory
+    """
+
     return '\n'.join(['{name} = {name}'.format(name=name)
-                      for name in sorted(os.listdir(directory), key=lambda name: name.lower())
+                      for name in sorted(os.listdir(directory),
+                                         key=lambda name: name.lower())
                       if not name.startswith('.')])
 
+
 def main(args=sys.argv[1:]):
+    """CLI"""
 
+    # parse command line
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument('directory', help='directory')
     parser.add_argument('-o', '--output', dest='output',
@@ -27,5 +33,13 @@
                         help='output')
     options = parser.parse_args(args)
 
+    # sanity
+    if not os.path.isdir(options.directory):
+        parser.error("Not a directory: '{}'".format(options.directory))
+
+    # output
+    options.output.write(index(options.directory))
+
+
 if __name__ == '__main__':
     main()
--- a/decoupage/web.py	Fri Mar 31 16:38:02 2017 -0700
+++ b/decoupage/web.py	Fri Mar 31 17:06:59 2017 -0700
@@ -103,10 +103,9 @@
             try:
                 _cls = _format.load()
                 _instance = _cls(self, **format_args.get(_format.name, {}))
-            except Exception, e:
+            except Exception as e:
                 # record the error, but persist
-                print >> sys.stderr, "Couldn't load format: %s" % _format
-                print >> sys.stderr, e
+                sys.stderr.write("Couldn't load format: {}\n{}\n".format(_format, e))
                 continue
             self.formats[_format.name] = _instance
 
@@ -118,10 +117,9 @@
                 template_dir = resource_filename(formatter.module_name, 'templates')
                 if template_dir not in self.template_directories and os.path.isdir(template_dir):
                     self.template_directories.append(template_dir)
-            except Exception, e:
+            except Exception as e:
                 # record the error, but persist
-                print >> sys.stderr, "Couldn't load formatter: %s" % formatter
-                print >> sys.stderr, e
+                sys.stderr.write("Couldn't load formatter: {}\n{}\n".format(formatter, e))
                 continue
             self.formatters[formatter.name] = _formatter
 
@@ -247,9 +245,9 @@
         try:
             template = self.loader.load(template)
             res = template.generate(**data).render('html', doctype='html')
-        except (TemplateError, TemplateSyntaxError, TemplateNotFound), e:
+        except (TemplateError, TemplateSyntaxError, TemplateNotFound) as e:
             if local_index:
-                print repr(e)
+                print (repr(e))
                 return self.fileserver(local_index)
             raise
         finally:
--- a/tox.ini	Fri Mar 31 16:38:02 2017 -0700
+++ b/tox.ini	Fri Mar 31 17:06:59 2017 -0700
@@ -1,2 +1,5 @@
+# https://tox.readthedocs.io/en/latest/
 [tox]
-envlist=py27,py35
+envlist=py27
+[testenv]
+commands=python setup.py test