Python bindings: Fix warnings from pep8
authorMichel Zou <xantares09@hotmail.com>
Fri, 19 Jul 2013 14:47:31 +0000 (16:47 +0200)
committerThomas Jarosch <thomas.jarosch@intra2net.com>
Fri, 19 Jul 2013 14:47:31 +0000 (16:47 +0200)
python/doxy2swig.py
python/examples/complete.py
python/examples/simple.py

index cf4c52b..440b5a2 100644 (file)
@@ -14,7 +14,7 @@ input.xml is your doxygen generated XML file and output.i is where the
 output will be written (the file will be clobbered).
 
 """
-######################################################################
+#
 #
 # This code is implemented using Mark Pilgrim's code as a guideline:
 #   http://www.faqs.org/docs/diveintopython/kgp_divein.html
@@ -27,7 +27,7 @@ output will be written (the file will be clobbered).
 #   Bill Spotz:  bug reports and testing.
 #   Sebastian Henschel:   Misc. enhancements.
 #
-######################################################################
+#
 
 from xml.dom import minidom
 import re
@@ -43,6 +43,7 @@ def my_open_read(source):
     else:
         return open(source)
 
+
 def my_open_write(dest):
     if hasattr(dest, "write"):
         return dest
@@ -50,14 +51,15 @@ def my_open_write(dest):
         return open(dest, 'w')
 
 
-class Doxy2SWIG:    
+class Doxy2SWIG:
+
     """Converts Doxygen generated XML files into a file containing
     docstrings that can be used by SWIG-1.3.x that have support for
     feature("docstring").  Once the data is parsed it is stored in
     self.pieces.
 
-    """    
-    
+    """
+
     def __init__(self, src, include_function_definition=True, quiet=False):
         """Initialize the instance given a source object.  `src` can
         be a file or filename.  If you do not want to include function
@@ -73,7 +75,7 @@ class Doxy2SWIG:
         f.close()
 
         self.pieces = []
-        self.pieces.append('\n// File: %s\n'%\
+        self.pieces.append('\n// File: %s\n' %
                            os.path.basename(f.name))
 
         self.space_re = re.compile(r'\s+')
@@ -92,22 +94,21 @@ class Doxy2SWIG:
             self.ignores.append('argsstring')
 
         self.quiet = quiet
-            
-        
+
     def generate(self):
         """Parses the file set in the initialization.  The resulting
         data is stored in `self.pieces`.
 
         """
         self.parse(self.xmldoc)
-    
+
     def parse(self, node):
         """Parse a given node.  This function in turn calls the
         `parse_<nodeType>` functions which handle the respective
         nodes.
 
         """
-        pm = getattr(self, "parse_%s"%node.__class__.__name__)
+        pm = getattr(self, "parse_%s" % node.__class__.__name__)
         pm(node)
 
     def parse_Document(self, node):
@@ -129,7 +130,7 @@ class Doxy2SWIG:
         `do_<tagName>` handers for different elements.  If no handler
         is available the `generic_parse` method is called.  All
         tagNames specified in `self.ignores` are simply ignored.
-        
+
         """
         name = node.tagName
         ignores = self.ignores
@@ -160,8 +161,8 @@ class Doxy2SWIG:
         `ELEMENT_NODEs`, that have a `tagName` equal to the name.
 
         """
-        nodes = [(x.tagName, x) for x in node.childNodes \
-                 if x.nodeType == x.ELEMENT_NODE and \
+        nodes = [(x.tagName, x) for x in node.childNodes
+                 if x.nodeType == x.ELEMENT_NODE and
                  x.tagName in names]
         return dict(nodes)
 
@@ -183,7 +184,7 @@ class Doxy2SWIG:
         if pad:
             npiece = len(self.pieces)
             if pad == 2:
-                self.add_text('\n')                
+                self.add_text('\n')
         for n in node.childNodes:
             self.parse(n)
         if pad:
@@ -203,7 +204,7 @@ class Doxy2SWIG:
     def do_compoundname(self, node):
         self.add_text('\n\n')
         data = node.firstChild.data
-        self.add_text('%%feature("docstring") %s "\n'%data)
+        self.add_text('%%feature("docstring") %s "\n' % data)
 
     def do_compounddef(self, node):
         kind = node.attributes['kind'].value
@@ -217,7 +218,7 @@ class Doxy2SWIG:
             for n in names:
                 if first.has_key(n):
                     self.parse(first[n])
-            self.add_text(['";','\n'])
+            self.add_text(['";', '\n'])
             for n in node.childNodes:
                 if n not in first.values():
                     self.parse(n)
@@ -231,13 +232,17 @@ class Doxy2SWIG:
         self.generic_parse(node, pad=1)
 
     def do_parameterlist(self, node):
-        text='unknown'
+        text = 'unknown'
         for key, val in node.attributes.items():
             if key == 'kind':
-                if val == 'param': text = 'Parameters'
-                elif val == 'exception': text = 'Exceptions'
-                elif val == 'retval': text = 'Returns'
-                else: text = val
+                if val == 'param':
+                    text = 'Parameters'
+                elif val == 'exception':
+                    text = 'Exceptions'
+                elif val == 'retval':
+                    text = 'Returns'
+                else:
+                    text = val
                 break
         self.add_text(['\n', '\n', text, ':', '\n'])
         self.generic_parse(node, pad=1)
@@ -249,13 +254,13 @@ class Doxy2SWIG:
     def do_parametername(self, node):
         self.add_text('\n')
         try:
-            data=node.firstChild.data
-        except AttributeError: # perhaps a <ref> tag in it
-            data=node.firstChild.firstChild.data
+            data = node.firstChild.data
+        except AttributeError:  # perhaps a <ref> tag in it
+            data = node.firstChild.firstChild.data
         if data.find('Exception') != -1:
             self.add_text(data)
         else:
-            self.add_text("%s: "%data)
+            self.add_text("%s: " % data)
 
     def do_parameterdefinition(self, node):
         self.generic_parse(node, pad=1)
@@ -273,11 +278,11 @@ class Doxy2SWIG:
         tmp = node.parentNode.parentNode.parentNode
         compdef = tmp.getElementsByTagName('compounddef')[0]
         cdef_kind = compdef.attributes['kind'].value
-        
+
         if prot == 'public':
             first = self.get_specific_nodes(node, ('definition', 'name'))
             name = first['name'].firstChild.data
-            if name[:8] == 'operator': # Don't handle operators yet.
+            if name[:8] == 'operator':  # Don't handle operators yet.
                 return
 
             if not 'definition' in first or \
@@ -290,7 +295,7 @@ class Doxy2SWIG:
                 defn = ""
             self.add_text('\n')
             self.add_text('%feature("docstring") ')
-            
+
             anc = node.parentNode.parentNode
             if cdef_kind in ('file', 'namespace'):
                 ns_node = anc.getElementsByTagName('innernamespace')
@@ -298,23 +303,23 @@ class Doxy2SWIG:
                     ns_node = anc.getElementsByTagName('compoundname')
                 if ns_node:
                     ns = ns_node[0].firstChild.data
-                    self.add_text(' %s::%s "\n%s'%(ns, name, defn))
+                    self.add_text(' %s::%s "\n%s' % (ns, name, defn))
                 else:
-                    self.add_text(' %s "\n%s'%(name, defn))
+                    self.add_text(' %s "\n%s' % (name, defn))
             elif cdef_kind in ('class', 'struct'):
                 # Get the full function name.
                 anc_node = anc.getElementsByTagName('compoundname')
                 cname = anc_node[0].firstChild.data
-                self.add_text(' %s::%s "\n%s'%(cname, name, defn))
+                self.add_text(' %s::%s "\n%s' % (cname, name, defn))
 
             for n in node.childNodes:
                 if n not in first.values():
                     self.parse(n)
             self.add_text(['";', '\n'])
-        
+
     def do_definition(self, node):
         data = node.firstChild.data
-        self.add_text('%s "\n%s'%(data, data))
+        self.add_text('%s "\n%s' % (data, data))
 
     def do_sectiondef(self, node):
         kind = node.attributes['kind'].value
@@ -326,14 +331,14 @@ class Doxy2SWIG:
         which should not be printed as such, so we comment it in the
         output."""
         data = node.firstChild.data
-        self.add_text('\n/*\n %s \n*/\n'%data)
+        self.add_text('\n/*\n %s \n*/\n' % data)
         # If our immediate sibling is a 'description' node then we
         # should comment that out also and remove it from the parent
         # node's children.
         parent = node.parentNode
         idx = parent.childNodes.index(node)
         if len(parent.childNodes) >= idx + 2:
-            nd = parent.childNodes[idx+2]
+            nd = parent.childNodes[idx + 2]
             if nd.nodeName == 'description':
                 nd = parent.removeChild(nd)
                 self.add_text('\n/*')
@@ -372,7 +377,7 @@ class Doxy2SWIG:
             if not os.path.exists(fname):
                 fname = os.path.join(self.my_dir,  fname)
             if not self.quiet:
-                print( "parsing file: %s"%fname )
+                print("parsing file: %s" % fname)
             p = Doxy2SWIG(fname, self.include_function_definition, self.quiet)
             p.generate()
             self.pieces.extend(self.clean_pieces(p.pieces))
@@ -389,7 +394,7 @@ class Doxy2SWIG:
         """Cleans the list of strings given as `pieces`.  It replaces
         multiple newlines by a maximum of 2 and returns a new list.
         It also wraps the paragraphs nicely.
-        
+
         """
         ret = []
         count = 0
@@ -403,7 +408,7 @@ class Doxy2SWIG:
                 elif count > 2:
                     ret.append('\n\n')
                 elif count:
-                    ret.append('\n'*count)
+                    ret.append('\n' * count)
                 count = 0
                 ret.append(i)
 
@@ -411,8 +416,8 @@ class Doxy2SWIG:
         ret = []
         for i in _data.split('\n\n'):
             if i == 'Parameters:' or i == 'Exceptions:' or i == 'Returns:':
-                ret.extend([i, '\n'+'-'*len(i), '\n\n'])
-            elif i.find('// File:') > -1: # leave comments alone.
+                ret.extend([i, '\n' + '-' * len(i), '\n\n'])
+            elif i.find('// File:') > -1:  # leave comments alone.
                 ret.extend([i, '\n'])
             else:
                 _tmp = textwrap.fill(i.strip(), break_long_words=False)
@@ -426,6 +431,7 @@ def convert(input, output, include_function_definition=True, quiet=False):
     p.generate()
     p.write(output)
 
+
 def main():
     usage = __doc__
     parser = optparse.OptionParser(usage)
@@ -439,13 +445,13 @@ def main():
                       default=False,
                       dest='quiet',
                       help='be quiet and minimize output')
-    
+
     options, args = parser.parse_args()
     if len(args) != 2:
         parser.error("error: no input and output specified")
 
     convert(args[0], args[1], not options.func_def, options.quiet)
-    
+
 
 if __name__ == '__main__':
     main()
index afa59fa..d949fca 100644 (file)
@@ -14,102 +14,108 @@ import ftdi1 as ftdi
 import time
 
 # version
-print ( 'version: %s\n' % ftdi.__version__  )
+print ('version: %s\n' % ftdi.__version__)
 
 # initialize
 ftdic = ftdi.new()
 if ftdic == 0:
-    print( 'new failed: %d' % ret )
-    os._exit( 1 )
+    print('new failed: %d' % ret)
+    os._exit(1)
 
 # try to list ftdi devices 0x6010 or 0x6001
-ret, devlist = ftdi.usb_find_all( ftdic, 0x0403, 0x6010 )
+ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6010)
 if ret <= 0:
-    ret, devlist = ftdi.usb_find_all( ftdic, 0x0403, 0x6001)
+    ret, devlist = ftdi.usb_find_all(ftdic, 0x0403, 0x6001)
 
 if ret < 0:
-    print( 'ftdi_usb_find_all failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
-    os._exit( 1 )
-print( 'devices: %d' % ret )
+    print('ftdi_usb_find_all failed: %d (%s)' %
+          (ret, ftdi.get_error_string(ftdic)))
+    os._exit(1)
+print('devices: %d' % ret)
 curnode = devlist
 i = 0
-while( curnode != None ):
-    ret, manufacturer, description, serial = ftdi.usb_get_strings( ftdic, curnode.dev )
+while(curnode != None):
+    ret, manufacturer, description, serial = ftdi.usb_get_strings(
+        ftdic, curnode.dev)
     if ret < 0:
-        print( 'ftdi_usb_get_strings failed: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
-        os._exit( 1 )
-    print( '#%d: manufacturer="%s" description="%s" serial="%s"\n' % ( i, manufacturer, description, serial ) )
+        print('ftdi_usb_get_strings failed: %d (%s)' %
+              (ret, ftdi.get_error_string(ftdic)))
+        os._exit(1)
+    print('#%d: manufacturer="%s" description="%s" serial="%s"\n' %
+          (i, manufacturer, description, serial))
     curnode = curnode.next
     i += 1
 
 # open usb
-ret = ftdi.usb_open( ftdic, 0x0403, 0x6001 )
+ret = ftdi.usb_open(ftdic, 0x0403, 0x6001)
 if ret < 0:
-    print( 'unable to open ftdi device: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
-    os._exit( 1 )
+    print('unable to open ftdi device: %d (%s)' %
+          (ret, ftdi.get_error_string(ftdic)))
+    os._exit(1)
 
 
 # bitbang
-ret = ftdi.set_bitmode( ftdic, 0xff, ftdi.BITMODE_BITBANG )
+ret = ftdi.set_bitmode(ftdic, 0xff, ftdi.BITMODE_BITBANG)
 if ret < 0:
-    print( 'Cannot enable bitbang' )
-    os._exit( 1 )
-print( 'turning everything on' )
-ftdi.write_data( ftdic, chr(0xff), 1 )
-time.sleep( 1 )
-print( 'turning everything off\n' )
-ftdi.write_data( ftdic, chr(0x00), 1 )
-time.sleep( 1 )
-for i in range( 8 ):
-    val = 2**i
-    print( 'enabling bit #%d (0x%02x)' % (i, val) )
-    ftdi.write_data( ftdic, chr(val), 1 )
-    time.sleep ( 1 )
-ftdi.disable_bitbang( ftdic )
-print( '' )
+    print('Cannot enable bitbang')
+    os._exit(1)
+print('turning everything on')
+ftdi.write_data(ftdic, chr(0xff), 1)
+time.sleep(1)
+print('turning everything off\n')
+ftdi.write_data(ftdic, chr(0x00), 1)
+time.sleep(1)
+for i in range(8):
+    val = 2 ** i
+    print('enabling bit #%d (0x%02x)' % (i, val))
+    ftdi.write_data(ftdic, chr(val), 1)
+    time.sleep(1)
+ftdi.disable_bitbang(ftdic)
+print('')
 
 
 # read pins
-ret, pins = ftdi.read_pins( ftdic )
-if ( ret == 0 ):
-    if sys.version_info[0] < 3: # python 2
-        pins = ord( pins )
+ret, pins = ftdi.read_pins(ftdic)
+if (ret == 0):
+    if sys.version_info[0] < 3:  # python 2
+        pins = ord(pins)
     else:
         pins = pins[0]
-    print( 'pins: 0x%x' % pins )
-              
+    print('pins: 0x%x' % pins)
+
 
 # read chip id
-ret, chipid = ftdi.read_chipid( ftdic )
-if (ret==0):
-    print( 'chip id: %x\n' % chipid )
+ret, chipid = ftdi.read_chipid(ftdic)
+if (ret == 0):
+    print('chip id: %x\n' % chipid)
 
 
 # read eeprom
 eeprom_addr = 1
-ret, eeprom_val = ftdi.read_eeprom_location( ftdic, eeprom_addr )
-if (ret==0):
-    print( 'eeprom @ %d: 0x%04x\n' % ( eeprom_addr, eeprom_val ) )
+ret, eeprom_val = ftdi.read_eeprom_location(ftdic, eeprom_addr)
+if (ret == 0):
+    print('eeprom @ %d: 0x%04x\n' % (eeprom_addr, eeprom_val))
 
-print( 'eeprom:' )
-ret = ftdi.read_eeprom( ftdic )
+print('eeprom:')
+ret = ftdi.read_eeprom(ftdic)
 size = 128
-ret, eeprom = ftdi.get_eeprom_buf ( ftdic, size )
-if ( ret == 0 ):
-    for i in range( size ):
+ret, eeprom = ftdi.get_eeprom_buf(ftdic, size)
+if (ret == 0):
+    for i in range(size):
         octet = eeprom[i]
-        if sys.version_info[0] < 3: # python 2
-            octet = ord( octet )
-        sys.stdout.write( '%02x ' % octet )
-        if ( i % 8 == 7 ):
-            print( '' )
-print( '' )
-            
+        if sys.version_info[0] < 3:  # python 2
+            octet = ord(octet)
+        sys.stdout.write('%02x ' % octet)
+        if (i % 8 == 7):
+            print('')
+print('')
+
 # close usb
-ret = ftdi.usb_close( ftdic )
+ret = ftdi.usb_close(ftdic)
 if ret < 0:
-    print( 'unable to close ftdi device: %d (%s)' % ( ret, ftdi.get_error_string( ftdic ) ) )
-    os._exit( 1 )
-    
-print ('device closed')    
-ftdi.free( ftdic )
+    print('unable to close ftdi device: %d (%s)' %
+          (ret, ftdi.get_error_string(ftdic)))
+    os._exit(1)
+
+print ('device closed')
+ftdi.free(ftdic)
index 9298c24..d555a69 100644 (file)
@@ -10,21 +10,22 @@ You need to build and install the wrapper first"""
 
 import ftdi1 as ftdi
 
+
 def main():
     """Main program"""
     context = ftdi.new()
 
     version_info = ftdi.get_library_version()
-    print("[FTDI version] major: %d, minor: %d, micro: %d" \
-               ", version_str: %s, snapshot_str: %s" %
-               (version_info.major, version_info.minor, version_info.micro,
-               version_info.version_str, version_info.snapshot_str))
+    print("[FTDI version] major: %d, minor: %d, micro: %d"
+          ", version_str: %s, snapshot_str: %s" %
+         (version_info.major, version_info.minor, version_info.micro,
+          version_info.version_str, version_info.snapshot_str))
 
     # try to open an ftdi 0x6010 or 0x6001
     ret = ftdi.usb_open(context, 0x0403, 0x6010)
     if ret < 0:
         ret = ftdi.usb_open(context, 0x0403, 0x6001)
-        
+
     print("ftdi.usb_open(): %d" % ret)
     print("ftdi.set_baudrate(): %d" % ftdi.set_baudrate(context, 9600))