@@ -390,9 +390,11 @@ def writeTo(self, output, indent):
390390 output .write ('\n ' )
391391 Source .writeTo (self , output , indent )
392392 self .writeExtraLines ('moduleEpilogue' , output )
393-
393+ if self .config .last ('writeMainMethodScript' ):
394+ self .writeMainBlock (output )
395+
394396 def writeExtraLines (self , name , output ):
395- """ writes an sequence of lines given a config attribute name
397+ """ writes a sequence of lines given a config attribute name
396398
397399 Lines may be callable. Refer to the defaultconfig module for
398400 details.
@@ -409,7 +411,29 @@ def writeExtraLines(self, name, output):
409411 pass
410412 output .write ('%s\n ' % (line , ))
411413
414+ def writeMainBlock (self , output ):
415+ """ writes a block to call the module as a script
412416
417+ @param output writable file-like object
418+ @return None
419+ """
420+ try :
421+ cls = [c for c in self .lines if getattr (c , 'isClass' , None )][0 ]
422+ methods = [m for m in cls .lines if getattr (m , 'isMethod' , None )]
423+ main = [m for m in methods if m .name == 'main' ][0 ]
424+ except (Exception , ):
425+ pass
426+ else :
427+ mods = main .modifiers
428+ typ = main .type
429+ if ('public' in mods ) and ('static' in mods ) and (typ == 'void' ):
430+ name = cls .name
431+ offset = self .I (1 )
432+ output .write ("if __name__ == '__main__':\n " )
433+ output .write ("%simport sys\n " % offset )
434+ output .write ("%s%s.main(sys.argv)\n " % (offset , name ))
435+
436+
413437class Class (Source ):
414438 """ Class -> specialized block type
415439
@@ -550,9 +574,12 @@ class Method(Source):
550574 """ Method -> specialized block type
551575
552576 """
577+ instanceFirstParam = ('object' , 'self' )
578+ classFirstParam = ('type' , 'cls' )
579+
553580 def __init__ (self , parent , name ):
554581 Source .__init__ (self , parent = parent , name = name )
555- self .parameters = [( 'object' , ' self' ) , ]
582+ self .parameters = [self . instanceFirstParam , ]
556583
557584 def addModifier (self , name ):
558585 """ adds named modifier to method
@@ -570,6 +597,9 @@ def addModifier(self, name):
570597 else :
571598 if deco not in self .preamble :
572599 self .preamble .append (deco )
600+ if (deco == '@classmethod' ) and (self .parameters ) \
601+ and (self .parameters [0 ] == self .instanceFirstParam ):
602+ self .parameters [0 ] = self .classFirstParam
573603 Source .addModifier (self , name )
574604
575605 def addParameter (self , typ , name ):
0 commit comments