code
stringlengths
1
1.72M
language
stringclasses
1 value
# empty
Python
""" a generic recursive descent parser the grammar is defined as a composition of objects the objects of the grammar are : Alternative : as in S -> A | B | C Sequence : as in S -> A B C KleeneStar : as in S -> A* or S -> A+ Token : a lexer token """ try: from pypy.interpreter.baseobjspace import Wrappable from pypy.interpreter.pyparser.pytoken import NULLTOKEN except ImportError: # allows standalone testing Wrappable = object NULLTOKEN = -1 # None from syntaxtree import SyntaxNode, TempSyntaxNode, TokenNode DEBUG = 0 USE_LOOKAHEAD = True def get_symbol( codename, symbols ): """Helper function to build a token name""" if codename in symbols: return symbols[codename] else: return "["+str(codename)+"]" #### Abstract interface for a lexer/tokenizer class TokenSource(object): """Abstract base class for a source tokenizer""" def context(self): """Returns a context to restore the state of the object later""" def restore(self, ctx): """Restore the context""" def next(self): """Returns the next token from the source a token is a tuple : (type,value) or (None,None) if the end of the source has been found """ def offset(self, ctx=None): """Returns the position we're at so far in the source optionnally provide a context and you'll get the offset of the context""" return -1 def current_linesource(self): """Returns the current line""" return "" def current_lineno(self): """Returns the current line number""" return 0 def get_pos(self): """Returns the current source position of the scanner""" return 0 def get_source_text(self, pos1, pos2 ): """Returns the source text between two scanner positions""" return "" ###################################################################### def build_first_sets(rules): """XXX : dead builds the real first tokens set for each rule in <rules> Because a rule can be recursive (directly or indirectly), the *simplest* algorithm to build each first set is to recompute them until Computation(N) = Computation(N-1), N being the number of rounds. As an example, on Python2.3's grammar, we need 19 cycles to compute full first sets. """ changed = True while changed: # loop while one first set is changed changed = False for rule in rules: # For each rule, recompute first set size = len(rule.first_set) rule.calc_first_set() new_size = len(rule.first_set) if new_size != size: changed = True for r in rules: assert len(r.first_set) > 0, "Error: ot Empty firstset for %s" % r r.reorder_rule() class AbstractContext(object): """Abstract base class. derived objects put some attributes here that users can use to save restore states""" pass from pypy.interpreter.baseobjspace import Wrappable class AbstractBuilder(Wrappable): """Abstract base class for builder objects""" def __init__(self, parser, debug=0 ): # This attribute is here for convenience self.debug = debug # the parser that represent the grammar used # Commented the assert: this eases the testing #assert isinstance( parser, Parser ) self.parser = parser def context(self): """Return an opaque context object""" pass def restore(self, ctx): """Accept an opaque context object""" pass def alternative(self, rule, source): return False def sequence(self, rule, source, elts_number): return False def token(self, name, value, source): return False # # we use the term root for a grammar rule to specify rules that are given a name # by the grammar # a rule like S -> A B* is mapped as Sequence( SCODE, KleeneStar(-3, B)) # so S is a root and the subrule describing B* is not. # SCODE is the numerical value for rule "S" class BaseGrammarBuilderContext(AbstractContext): def __init__(self, stackpos ): self.stackpos = stackpos class BaseGrammarBuilder(AbstractBuilder): """Base/default class for a builder""" # XXX (adim): this is trunk's keyword management keywords = None def __init__(self, parser, debug=0 ): AbstractBuilder.__init__(self, parser, debug ) # stacks contain different objects depending on the builder class # to be RPython they should not be defined in the base class self.stack = [] def context(self): """Returns the state of the builder to be restored later""" return BaseGrammarBuilderContext(len(self.stack)) def restore(self, ctx): assert isinstance(ctx, BaseGrammarBuilderContext) del self.stack[ctx.stackpos:] def alternative(self, rule, source): # Do nothing, keep rule on top of the stack if rule.is_root(): elems = self.stack[-1].expand() self.stack[-1] = SyntaxNode(rule.codename, elems, source.current_lineno()) if self.debug: self.stack[-1].dumpstr() return True def sequence(self, rule, source, elts_number): """ """ items = [] slice_start = len(self.stack) - elts_number assert slice_start >= 0 for node in self.stack[slice_start:]: items += node.expand() is_root = rule.is_root() # replace N elements with 1 element regrouping them if elts_number >= 1: if is_root: elem = SyntaxNode(rule.codename, items, source.current_lineno()) else: elem = TempSyntaxNode(rule.codename, items, source.current_lineno()) del self.stack[slice_start:] self.stack.append(elem) elif elts_number == 0: if is_root: self.stack.append(SyntaxNode(rule.codename, [], source.current_lineno())) else: self.stack.append(TempSyntaxNode(rule.codename, [], source.current_lineno())) if self.debug: self.stack[-1].dumpstr() return True def token(self, name, value, source): self.stack.append(TokenNode(name, value, source.current_lineno())) if self.debug: self.stack[-1].dumpstr() return True ####################################################################### # Grammar Elements Classes (Alternative, Sequence, KleeneStar, Token) # ####################################################################### class GrammarElement(Wrappable): """Base parser class""" symbols = {} # dirty trick to provide a symbols mapping while printing (and not putting it in every object) def __init__(self, parser, codename): # the rule name #assert type(codename)==int assert isinstance(parser, Parser) self.parser = parser self.codename = codename # integer mapping to either a token value or rule symbol value self.args = [] self.first_set = [] self.first_set_complete = False # self._processing = False self._trace = False def is_root(self): """This is a root node of the grammar, that is one that will be included in the syntax tree""" # code attributed to root grammar rules are >=0 if self.codename >=0: return True return False def match(self, source, builder, level=0): """Try to match a grammar rule If next set of tokens matches this grammar element, use <builder> to build an appropriate object, otherwise returns None. /!\ If the sets of element didn't match the current grammar element, then the <source> is restored as it was before the call to the match() method returns None if no match or an object build by builder """ if not USE_LOOKAHEAD: return self._match(source, builder, level) pos1 = -1 # make the annotator happy pos2 = -1 # make the annotator happy token = source.peek() if self._trace: pos1 = source.get_pos() in_first_set = self.match_first_set(builder, token) if not in_first_set: # and not EmptyToken in self.first_set: if self.parser.EmptyToken in self.first_set: ret = builder.sequence(self, source, 0 ) if self._trace: self._debug_display(token, level, 'eee' ) return ret if self._trace: self._debug_display(token, level, 'rrr' ) return 0 elif self._trace: self._debug_display(token, level, '>>>') res = self._match(source, builder, level) if self._trace: pos2 = source.get_pos() if res: prefix = '+++' else: prefix = '---' self._debug_display(token, level, prefix) print ' '*level, prefix, " TEXT ='%s'" % ( source.get_source_text(pos1,pos2)) if res: print "*" * 50 return res def _debug_display(self, token, level, prefix): """prints context debug informations""" prefix = '%s%s' % (' ' * level, prefix) print prefix, " RULE =", self print prefix, " TOKEN =", token print prefix, " FIRST SET =", self.first_set def _match(self, source, builder, level=0): """Try to match a grammar rule If next set of tokens matches this grammar element, use <builder> to build an appropriate object, otherwise returns 0. /!\ If the sets of element didn't match the current grammar element, then the <source> is restored as it was before the call to the match() method returns None if no match or an object build by builder """ return 0 def parse(self, source): """Returns a simplified grammar if the rule matched at the source current context or None""" # **NOT USED** **NOT IMPLEMENTED** # To consider if we need to improve speed in parsing pass def __str__(self): try: return self.display(0) except Exception, e: import traceback traceback.print_exc() def __repr__(self): try: return self.display(0) except Exception, e: import traceback traceback.print_exc() def display(self, level=0): """Helper function used to represent the grammar. mostly used for debugging the grammar itself""" return "GrammarElement" def debug_return(self, ret, arg="" ): # FIXME: use a wrapper of match() methods instead of debug_return() # to prevent additional indirection even better a derived # Debugging builder class if ret and DEBUG > 0: print "matched %s (%s): %s" % (self.__class__.__name__, arg, self.display(0) ) return ret def calc_first_set(self): """returns the list of possible next tokens *must* be implemented in subclasses """ # XXX: first_set could probably be implemented with sets return [] def match_first_set(self, builder, other): """matching is not equality: token('NAME','x') matches token('NAME',None) """ for tk in self.first_set: if tk.match_token(builder, other): return True return False def in_first_set(self, other): return other in self.first_set def reorder_rule(self): """Called after the computation of first set to allow rules to be reordered to avoid ambiguities """ pass def validate( self, syntax_node ): """validate a syntax tree/subtree from this grammar node""" pass class GrammarProxy(GrammarElement): def __init__(self, parser, rule_name, codename=-1 ): GrammarElement.__init__(self, parser, codename ) self.rule_name = rule_name self.object = None def display(self, level=0): """Helper function used to represent the grammar. mostly used for debugging the grammar itself""" name = self.parser.symbol_repr(self.codename) repr = "Proxy("+name if self.object: repr+=","+self.object.display(1) repr += ")" return repr class Alternative(GrammarElement): """Represents an alternative in a grammar rule (as in S -> A | B | C)""" def __init__(self, parser, name, args): GrammarElement.__init__(self, parser, name ) self.args = args self._reordered = False for i in self.args: assert isinstance( i, GrammarElement ) def _match(self, source, builder, level=0 ): """If any of the rules in self.args matches returns the object built from the first rules that matches """ if DEBUG > 1: print "try alt:", self.display(level) tok = source.peek() # Here we stop at the first match we should # try instead to get the longest alternative # to see if this solve our problems with infinite recursion for rule in self.args: if USE_LOOKAHEAD: if not rule.match_first_set(builder, tok) and self.parser.EmptyToken not in rule.first_set: if self._trace: print "Skipping impossible rule: %s" % (rule,) continue m = rule.match(source, builder, level+1) if m: ret = builder.alternative( self, source ) return ret return 0 def display(self, level=0): name = self.parser.symbol_repr( self.codename ) if level == 0: name = name + " -> " elif self.is_root(): return name else: name = "" items = [ a.display(1) for a in self.args ] return name+"(" + "|".join( items ) + ")" def calc_first_set(self): """returns the list of possible next tokens if S -> (A | B | C): LAH(S) = Union( LAH(A), LAH(B), LAH(C) ) """ # do this to avoid problems on indirect recursive rules for rule in self.args: for t in rule.first_set: if t not in self.first_set: self.first_set.append(t) # self.first_set[t] = 1 def reorder_rule(self): # take the opportunity to reorder rules in alternatives # so that rules with Empty in their first set come last # warn if two rules have empty in their first set empty_set = [] not_empty_set = [] # <tokens> is only needed for warning / debugging purposes tokens_set = [] for rule in self.args: if self.parser.EmptyToken in rule.first_set: empty_set.append(rule) else: not_empty_set.append(rule) if DEBUG: # This loop is only neede dfor warning / debugging purposes # It will check if a token is part of several first sets of # a same alternative for token in rule.first_set: if token is not self.parser.EmptyToken and token in tokens_set: print "Warning, token %s in\n\t%s's first set is " \ " part of a previous rule's first set in " \ " alternative\n\t%s" % (token, rule, self) tokens_set.append(token) if len(empty_set) > 1 and not self._reordered: print "Warning: alternative %s has more than one rule " \ "matching Empty" % self self._reordered = True # self.args[:] = not_empty_set for elt in self.args[:]: self.args.remove(elt) for elt in not_empty_set: self.args.append(elt) self.args.extend( empty_set ) def validate( self, syntax_node ): """validate a syntax tree/subtree from this grammar node""" if self.codename != syntax_node.name: return False if len(syntax_node.nodes) != 1: return False node = syntax_node.nodes[0] for alt in self.args: if alt.validate( node ): return True return False class Sequence(GrammarElement): """Reprensents a Sequence in a grammar rule (as in S -> A B C)""" def __init__(self, parser, name, args): GrammarElement.__init__(self, parser, name ) self.args = args for i in self.args: assert isinstance( i, GrammarElement ) def _match(self, source, builder, level=0): """matches all of the symbols in order""" if DEBUG > 1: print "try seq:", self.display(0) ctx = source.context() bctx = builder.context() for rule in self.args: m = rule.match(source, builder, level+1) if not m: # Restore needed because some rules may have been matched # before the one that failed source.restore(ctx) builder.restore(bctx) return 0 ret = builder.sequence(self, source, len(self.args)) return ret def display(self, level=0): name = self.parser.symbol_repr( self.codename ) if level == 0: name = name + " -> " elif self.is_root(): return name else: name = "" items = [a.display(1) for a in self.args] return name + "(" + " ".join( items ) + ")" def calc_first_set(self): """returns the list of possible next tokens if S -> A* B C: LAH(S) = Union( LAH(A), LAH(B) ) if S -> A+ B C: LAH(S) = LAH(A) if S -> A B C: LAH(S) = LAH(A) """ for rule in self.args: if not rule.first_set: break if self.parser.EmptyToken in self.first_set: self.first_set.remove( self.parser.EmptyToken ) # del self.first_set[self.parser.EmptyToken] # while we're in this loop, keep agregating possible tokens for t in rule.first_set: if t not in self.first_set: self.first_set.append(t) # self.first_set[t] = 1 if self.parser.EmptyToken not in rule.first_set: break def validate( self, syntax_node ): """validate a syntax tree/subtree from this grammar node""" if self.codename != syntax_node.name: return False if len(syntax_node.nodes) != len(self.args): return False for i in xrange(len(self.args)): rule = self.args[i] node = syntax_node.nodes[i] if not rule.validate( node ): return False return True class KleeneStar(GrammarElement): """Represents a KleeneStar in a grammar rule as in (S -> A+) or (S -> A*)""" def __init__(self, parser, name, _min = 0, _max = -1, rule=None): GrammarElement.__init__( self, parser, name ) self.args = [rule] self.min = _min if _max == 0: raise ValueError("KleeneStar needs max==-1 or max>1") self.max = _max self.star = "x" if self.min == 0: self.first_set.append( self.parser.EmptyToken ) # self.first_set[self.parser.EmptyToken] = 1 def _match(self, source, builder, level=0): """matches a number of times self.args[0]. the number must be comprised between self._min and self._max inclusive. -1 is used to represent infinity """ if DEBUG > 1: print "try kle:", self.display(0) ctx = None bctx = None if self.min: ctx = source.context() bctx = builder.context() rules = 0 rule = self.args[0] while True: m = rule.match(source, builder, level+1) if not m: # Rule should be matched at least 'min' times if rules<self.min: source.restore(ctx) builder.restore(bctx) return 0 ret = builder.sequence(self, source, rules) return ret rules += 1 if self.max>0 and rules == self.max: ret = builder.sequence(self, source, rules) return ret def display(self, level=0): name = self.parser.symbol_repr( self.codename ) if level==0: name = name + " -> " elif self.is_root(): return name else: name = "" star = self.get_star() s = self.args[0].display(1) return name + "%s%s" % (s, star) def get_star(self): star = "{%d,%d}" % (self.min,self.max) if self.min==0 and self.max==1: star = "?" elif self.min==0 and self.max==-1: star = "*" elif self.min==1 and self.max==-1: star = "+" return star def calc_first_set(self): """returns the list of possible next tokens if S -> A*: LAH(S) = Union( LAH(A), self.parser.EmptyToken ) if S -> A+: LAH(S) = LAH(A) """ rule = self.args[0] self.first_set = rule.first_set[:] # self.first_set = dict(rule.first_set) if self.min == 0 and self.parser.EmptyToken not in self.first_set: self.first_set.append(self.parser.EmptyToken) # self.first_set[self.parser.EmptyToken] = 1 def validate( self, syntax_node ): """validate a syntax tree/subtree from this grammar node""" if self.codename != syntax_node.name: return False rule = self.args[0] if self.min > len(syntax_node.nodes): return False if self.max>=0 and self.max<len(syntax_node.nodes): return False for n in self.node: if not rule.validate(n): return False return True class Token(GrammarElement): """Represents a Token in a grammar rule (a lexer token)""" def __init__(self, parser, codename, value=None): GrammarElement.__init__(self, parser, codename) self.value = value self.first_set = [self] # self.first_set = {self: 1} def match(self, source, builder, level=0): """Matches a token. the default implementation is to match any token whose type corresponds to the object's name. You can extend Token to match anything returned from the lexer. for exemple type, value = source.next() if type=="integer" and int(value)>=0: # found else: # error unknown or negative integer """ # XXX (adim): this is trunk's keyword management # if (self.value is not None and builder.keywords is not None # and self.value not in builder.keywords): # return 0 ctx = source.context() tk = source.next() if tk.codename == self.codename: if self.value is None: ret = builder.token( tk.codename, tk.value, source ) return ret elif self.value == tk.value: ret = builder.token( tk.codename, tk.value, source ) return ret if DEBUG > 1: print "tried tok:", self.display() source.restore( ctx ) return 0 def display(self, level=0): name = self.parser.symbol_repr( self.codename ) if self.value is None: return "<%s>" % name else: return "<%s>=='%s'" % (name, self.value) def match_token(self, builder, other): """convenience '==' implementation, this is *not* a *real* equality test a Token instance can be compared to: - another Token instance in which case all fields (name and value) must be equal - a tuple, such as those yielded by the Python lexer, in which case the comparison algorithm is similar to the one in match() """ if not isinstance(other, Token): raise RuntimeError("Unexpected token type") if other is self.parser.EmptyToken: return False # XXX (adim): this is trunk's keyword management # if (self.value is not None and builder.keywords is not None # and self.value not in builder.keywords): # return False res = other.codename == self.codename and self.value in [None, other.value] #print "matching", self, other, res return res def __eq__(self, other): return self.codename == other.codename and self.value == other.value def calc_first_set(self): """computes the list of possible next tokens """ pass def validate( self, syntax_node ): """validate a syntax tree/subtree from this grammar node""" if self.codename != syntax_node.name: return False if self.value is None: return True if self.value == syntax_node.value: return True return False class Parser(object): def __init__(self): pass _anoncount = self._anoncount = -10 _count = self._count = 0 self.sym_name = {} # mapping symbol code -> symbol name self.symbols = {} # mapping symbol name -> symbol code self.tokens = { 'NULLTOKEN' : -1 } self.EmptyToken = Token( self, -1, None ) self.tok_name = {} self.tok_values = {} self.tok_rvalues = {} self._ann_sym_count = -10 self._sym_count = 0 self.all_rules = [] self.root_rules = {} def symbol_repr( self, codename ): if codename in self.tok_name: return self.tok_name[codename] elif codename in self.sym_name: return self.sym_name[codename] return "%d" % codename def add_symbol( self, sym ): # assert isinstance( sym, str ) if not sym in self.symbols: val = self._sym_count self._sym_count += 1 self.symbols[sym] = val self.sym_name[val] = sym return val return self.symbols[ sym ] def add_anon_symbol( self, sym ): # assert isinstance( sym, str ) if not sym in self.symbols: val = self._ann_sym_count self._ann_sym_count -= 1 self.symbols[sym] = val self.sym_name[val] = sym return val return self.symbols[ sym ] def add_token( self, tok, value = None ): # assert isinstance( tok, str ) if not tok in self.tokens: val = self._sym_count self._sym_count += 1 self.tokens[tok] = val self.tok_name[val] = tok if value is not None: self.tok_values[value] = val # XXX : this reverse mapping seemed only to be used # because of pycodegen visitAugAssign self.tok_rvalues[val] = value return val return self.tokens[ tok ] def load_symbols( self, symbols ): for _value, _name in symbols.items(): if _value < self._ann_sym_count: self._ann_sym_count = _value - 1 if _value > self._sym_count: self._sym_count = _value + 1 self.symbols[_name] = _value self.sym_name[_value] = _name def build_first_sets(self): """builds the real first tokens set for each rule in <rules> Because a rule can be recursive (directly or indirectly), the *simplest* algorithm to build each first set is to recompute them until Computation(N) = Computation(N-1), N being the number of rounds. As an example, on Python2.3's grammar, we need 19 cycles to compute full first sets. """ rules = self.all_rules changed = True while changed: # loop while one first set is changed changed = False for rule in rules: # For each rule, recompute first set size = len(rule.first_set) rule.calc_first_set() new_size = len(rule.first_set) if new_size != size: changed = True for r in rules: assert len(r.first_set) > 0, "Error: ot Empty firstset for %s" % r r.reorder_rule() def build_alternative( self, name_id, args ): # assert isinstance( name_id, int ) assert isinstance(args, list) alt = Alternative( self, name_id, args ) self.all_rules.append( alt ) return alt def Alternative_n(self, name, args ): # assert isinstance(name, str) name_id = self.add_symbol( name ) return self.build_alternative( name_id, args ) def build_sequence( self, name_id, args ): # assert isinstance( name_id, int ) alt = Sequence( self, name_id, args ) self.all_rules.append( alt ) return alt def Sequence_n(self, name, args ): # assert isinstance(name, str) name_id = self.add_symbol( name ) return self.build_sequence( name_id, args ) def build_kleenestar( self, name_id, _min = 0, _max = -1, rule = None ): # assert isinstance( name_id, int ) alt = KleeneStar( self, name_id, _min, _max, rule ) self.all_rules.append( alt ) return alt def KleeneStar_n(self, name, _min = 0, _max = -1, rule = None ): # assert isinstance(name, str) name_id = self.add_symbol( name ) return self.build_kleenestar( name_id, _min, _max, rule ) def Token_n(self, name, value = None ): # assert isinstance( name, str) # assert value is None or isinstance( value, str) name_id = self.add_token( name, value ) return self.build_token( name_id, value ) def build_token(self, name_id, value = None ): # assert isinstance( name_id, int ) # assert value is None or isinstance( value, str) tok = Token( self, name_id, value ) return tok # Debugging functions def show_rules(self, name): import re rex = re.compile(name) rules =[] for _name, _val in self.symbols.items(): if rex.search(_name) and _val>=0: rules.append(self.root_rules[_val]) return rules
Python
# A replacement for the token module # # adds a new map token_values to avoid doing getattr on the module # from PyPy RPython N_TOKENS = 0 # This is used to replace None NULLTOKEN = -1 tok_name = {-1 : 'NULLTOKEN'} tok_values = {'NULLTOKEN' : -1} # tok_rpunct = {} def setup_tokens( parser ): # global tok_rpunct # For compatibility, this produces the same constant values as Python 2.4. parser.add_token( 'ENDMARKER' ) parser.add_token( 'NAME' ) parser.add_token( 'NUMBER' ) parser.add_token( 'STRING' ) parser.add_token( 'NEWLINE' ) parser.add_token( 'INDENT' ) parser.add_token( 'DEDENT' ) parser.add_token( 'LPAR', "(" ) parser.add_token( 'RPAR', ")" ) parser.add_token( 'LSQB', "[" ) parser.add_token( 'RSQB', "]" ) parser.add_token( 'COLON', ":" ) parser.add_token( 'COMMA', "," ) parser.add_token( 'SEMI', ";" ) parser.add_token( 'PLUS', "+" ) parser.add_token( 'MINUS', "-" ) parser.add_token( 'STAR', "*" ) parser.add_token( 'SLASH', "/" ) parser.add_token( 'VBAR', "|" ) parser.add_token( 'AMPER', "&" ) parser.add_token( 'LESS', "<" ) parser.add_token( 'GREATER', ">" ) parser.add_token( 'EQUAL', "=" ) parser.add_token( 'DOT', "." ) parser.add_token( 'PERCENT', "%" ) parser.add_token( 'BACKQUOTE', "`" ) parser.add_token( 'LBRACE', "{" ) parser.add_token( 'RBRACE', "}" ) parser.add_token( 'EQEQUAL', "==" ) ne = parser.add_token( 'NOTEQUAL', "!=" ) parser.tok_values["<>"] = ne parser.add_token( 'LESSEQUAL', "<=" ) parser.add_token( 'GREATEREQUAL', ">=" ) parser.add_token( 'TILDE', "~" ) parser.add_token( 'CIRCUMFLEX', "^" ) parser.add_token( 'LEFTSHIFT', "<<" ) parser.add_token( 'RIGHTSHIFT', ">>" ) parser.add_token( 'DOUBLESTAR', "**" ) parser.add_token( 'PLUSEQUAL', "+=" ) parser.add_token( 'MINEQUAL', "-=" ) parser.add_token( 'STAREQUAL', "*=" ) parser.add_token( 'SLASHEQUAL', "/=" ) parser.add_token( 'PERCENTEQUAL', "%=" ) parser.add_token( 'AMPEREQUAL', "&=" ) parser.add_token( 'VBAREQUAL', "|=" ) parser.add_token( 'CIRCUMFLEXEQUAL', "^=" ) parser.add_token( 'LEFTSHIFTEQUAL', "<<=" ) parser.add_token( 'RIGHTSHIFTEQUAL', ">>=" ) parser.add_token( 'DOUBLESTAREQUAL', "**=" ) parser.add_token( 'DOUBLESLASH', "//" ) parser.add_token( 'DOUBLESLASHEQUAL',"//=" ) parser.add_token( 'AT', "@" ) parser.add_token( 'OP' ) parser.add_token( 'ERRORTOKEN' ) # extra PyPy-specific tokens parser.add_token( "COMMENT" ) parser.add_token( "NL" ) # tok_rpunct = parser.tok_values.copy() # for _name, _value in parser.tokens.items(): # globals()[_name] = _value # setattr(parser, _name, _value)
Python
"""SyntaxTree class definition""" # try: # # from pypy.interpreter.pyparser.pysymbol import sym_values # from pypy.interpreter.pyparser.pytoken import tok_values # except ImportError: # # from pysymbol import sym_values # from pytoken import tok_values from pypy.tool.uid import uid from pypy.tool.uid import uid class AbstractSyntaxVisitor(object): def visit_syntaxnode( self, node ): pass def visit_tempsyntaxnode( self, node ): pass def visit_tokennode( self, node ): pass class SyntaxNode(object): """A syntax node""" def __init__(self, name, args, lineno=-1): self.name = name self.nodes = args self.lineno = lineno def dumptree(self, treenodes, indent): """helper function used to dump the syntax tree""" treenodes.append(str(self.name)) if len(self.nodes) > 1: treenodes.append(" -> (\n") treenodes.append(indent+" ") for node in self.nodes: node.dumptree(treenodes, indent+" ") treenodes.append(")\n") treenodes.append(indent) elif len(self.nodes) == 1: treenodes.append(" ->\n") treenodes.append(indent+" ") self.nodes[0].dumptree(treenodes, indent+" ") def dumpstr(self): """turns the tree repr into a string""" treenodes = [] self.dumptree(treenodes, "") return "".join(treenodes) def __repr__(self): return "<node [%s] at 0x%x>" % (self.name, uid(self)) def __str__(self): return "(%s)" % self.name def visit(self, visitor): assert isinstance(visitor, AbstractSyntaxVisitor) return visitor.visit_syntaxnode(self) def expand(self): """expand the syntax node to its content, do nothing here since we are a regular node and not a TempSyntaxNode""" return [ self ] def totuple(self, sym_values, lineno=False ): """returns a tuple representation of the syntax tree needs symbols+tokens value to name mapping to represent the nodes """ symvalue = sym_values.get( self.name, (0, self.name) ) l = [ symvalue ] l += [node.totuple(lineno, sym_values ) for node in self.nodes] return tuple(l) class TempSyntaxNode(SyntaxNode): """A temporary syntax node to represent intermediate rules""" def expand(self): """expand the syntax node to its content""" return self.nodes def visit(self, visitor): assert isinstance(visitor, AbstractSyntaxVisitor) return visitor.visit_tempsyntaxnode(self) class TokenNode(SyntaxNode): """A token node""" def __init__(self, name, value, lineno = -1): SyntaxNode.__init__(self, name, [], lineno) self.value = value def dumptree(self, treenodes, indent): """helper function used to dump the syntax tree""" if self.value: treenodes.append("%s='%s' (%d) " % (self.name, self.value, self.lineno)) else: treenodes.append("'%s' (%d) " % (self.name, self.lineno)) def __repr__(self): if self.value is not None: return "<%s=%s>" % ( self.name, repr(self.value)) else: return "<%s!>" % (self.name,) def visit(self, visitor): assert isinstance(visitor, AbstractSyntaxVisitor) return visitor.visit_tokennode(self) def totuple(self, tok_values, lineno=False): """returns a tuple representation of the syntax tree needs symbols+tokens value to name mapping to represent the nodes """ num = tok_values.get(self.name, -1) if num == -1: print "Unknown", self.name, self.value if self.value is not None: val = self.value else: if self.name not in ("NEWLINE", "INDENT", "DEDENT", "ENDMARKER"): val = self.name else: val = self.value or '' if lineno: return (num, val, self.lineno) else: return (num, val)
Python
from grammar import AbstractBuilder, AbstractContext, Parser class StackElement: """wraps TupleBuilder's tuples""" class Terminal(StackElement): def __init__(self, num, value, lineno=-1): self.nodes = [(num, value, lineno)] self.num = num def as_tuple(self, lineno=False): if lineno: return self.nodes[0] else: return self.nodes[0][:-1] def as_w_tuple(self, space, lineno=False): num, value, lineno = self.nodes[0] content = [space.wrap(num), space.wrap(value)] if lineno: content.append(space.wrap(lineno)) return space.newtuple(content) class NonTerminal(StackElement): def __init__(self, num, nodes): """rulename should always be None with regular Python grammar""" self.nodes = nodes self.num = num def as_tuple(self, lineno=False): l = [self.num] + [node.as_tuple(lineno) for node in self.nodes] return tuple(l) def as_w_tuple(self, space, lineno=False): l = [space.wrap(self.num)] l += [node.as_w_tuple(space, lineno) for node in self.nodes] return space.newtuple(l) def expand_nodes(stack_elements): """generate a nested tuples from a list of stack elements""" expanded = [] for element in stack_elements: if isinstance(element, NonTerminal) and element.num<0: expanded.extend(element.nodes) else: expanded.append(element) return expanded class TupleBuilderContext(AbstractContext): def __init__(self, stackpos ): self.stackpos = stackpos class TupleBuilder(AbstractBuilder): """A builder that directly produce the AST""" def __init__(self, parser, debug=0, lineno=True): AbstractBuilder.__init__(self, parser, debug) # This attribute is here for convenience self.source_encoding = None self.lineno = lineno self.stack = [] self.space_token = ( self.parser.tokens['NEWLINE'], self.parser.tokens['INDENT'], self.parser.tokens['DEDENT'], self.parser.tokens['ENDMARKER'] ) def context(self): """Returns the state of the builder to be restored later""" #print "Save Stack:", self.stack return TupleBuilderContext(len(self.stack)) def restore(self, ctx): assert isinstance(ctx, TupleBuilderContext) del self.stack[ctx.stackpos:] #print "Restore Stack:", self.stack def alternative(self, rule, source): # Do nothing, keep rule on top of the stack if rule.is_root(): nodes = expand_nodes( [self.stack[-1]] ) self.stack[-1] = NonTerminal( rule.codename, nodes ) return True def sequence(self, rule, source, elts_number): """ """ num = rule.codename node = [rule.codename] if elts_number > 0: sequence_elements = [self.stack.pop() for i in range(elts_number)] sequence_elements.reverse() nodes = expand_nodes( sequence_elements ) else: nodes = [] self.stack.append( NonTerminal(num, nodes) ) return True def token(self, codename, value, source): lineno = source._token_lnum if value is None: if codename not in self.space_token: value = self.parser.tok_rvalues.get(codename, "unknown op") else: value = '' self.stack.append( Terminal(codename, value, lineno) ) return True
Python
import autopath import py from test_astcompiler import compile_with_astcompiler def setup_module(mod): import sys if sys.version[:3] != "2.4": py.test.skip("expected to work only on 2.4") import pypy.conftest mod.std_space = pypy.conftest.gettestobjspace('std') def check_file_compile(filename): print 'Compiling:', filename source = open(filename).read() #check_compile(source, 'exec', quiet=True, space=std_space) compile_with_astcompiler(source, target='exec', space=std_space) def test_all(): p = py.path.local(autopath.pypydir).dirpath().join('lib-python', '2.4.1') for s in p.listdir(): if s.check(ext='.py'): yield check_file_compile, str(s)
Python
class FakeSpace: w_None = None w_str = str w_basestring = basestring w_int = int def wrap(self, obj): return obj def unwrap(self, obj): return obj def isinstance(self, obj, wtype ): return isinstance(obj,wtype) def is_true(self, obj): return obj def eq_w(self, obj1, obj2): return obj1 == obj2 def is_w(self, obj1, obj2): return obj1 is obj2 def type(self, obj): return type(obj) def newlist(self, lst): return list(lst) def newtuple(self, lst): return tuple(lst) def call_method(self, obj, meth, *args): return getattr(obj, meth)(*args) def call_function(self, func, *args): return func(*args) builtin = dict(int=int, long=long, float=float, complex=complex)
Python
"""test module for CPython / PyPy nested tuples comparison""" import os, os.path as osp import sys from pypy.interpreter.pyparser.pythonutil import python_parse, pypy_parse from pprint import pprint from pypy.interpreter.pyparser import grammar grammar.DEBUG = False from symbol import sym_name def name(elt): return "%s[%s]"% (sym_name.get(elt,elt),elt) def read_samples_dir(): return [osp.join('samples', fname) for fname in os.listdir('samples') if fname.endswith('.py')] def print_sym_tuple(nested, level=0, limit=15, names=False, trace=()): buf = [] if level <= limit: buf.append("%s(" % (" "*level)) else: buf.append("(") for index, elt in enumerate(nested): # Test if debugging and if on last element of error path if trace and not trace[1:] and index == trace[0]: buf.append('\n----> ') if type(elt) is int: if names: buf.append(name(elt)) else: buf.append(str(elt)) buf.append(', ') elif type(elt) is str: buf.append(repr(elt)) else: if level < limit: buf.append('\n') buf.extend(print_sym_tuple(elt, level+1, limit, names, trace[1:])) buf.append(')') return buf def assert_tuples_equal(tup1, tup2, curpos = ()): for index, (elt1, elt2) in enumerate(zip(tup1, tup2)): if elt1 != elt2: if type(elt1) is tuple and type(elt2) is tuple: assert_tuples_equal(elt1, elt2, curpos + (index,)) raise AssertionError('Found difference at %s : %s != %s' % (curpos, name(elt1), name(elt2) ), curpos) from time import time, clock def test_samples( samples ): time_reports = {} for sample in samples: print "testing", sample tstart1, cstart1 = time(), clock() pypy_tuples = pypy_parse(sample) tstart2, cstart2 = time(), clock() python_tuples = python_parse(sample) time_reports[sample] = (time() - tstart2, tstart2-tstart1, clock() - cstart2, cstart2-cstart1 ) #print "-"*10, "PyPy parse results", "-"*10 #print ''.join(print_sym_tuple(pypy_tuples, names=True)) #print "-"*10, "CPython parse results", "-"*10 #print ''.join(print_sym_tuple(python_tuples, names=True)) print try: assert_tuples_equal(pypy_tuples, python_tuples) except AssertionError,e: error_path = e.args[-1] print "ERROR PATH =", error_path print "="*80 print file(sample).read() print "="*80 print "-"*10, "PyPy parse results", "-"*10 print ''.join(print_sym_tuple(pypy_tuples, names=True, trace=error_path)) print "-"*10, "CPython parse results", "-"*10 print ''.join(print_sym_tuple(python_tuples, names=True, trace=error_path)) print "Failed on (%s)" % sample # raise pprint(time_reports) if __name__=="__main__": import getopt opts, args = getopt.getopt( sys.argv[1:], "d:", [] ) for opt, val in opts: if opt == "-d": pass # set_debug(int(val)) if args: samples = args else: samples = read_samples_dir() test_samples( samples )
Python
""" list of tested expressions / suites (used by test_parser and test_astbuilder) """ constants = [ "0", "7", "-3", "053", "0x18", "14L", "1.0", "3.9", "-3.6", "1.8e19", "90000000000000", "90000000000000.", "3j" ] expressions = [ "x = a + 1", "x = 1 - a", "x = a * b", "x = a ** 2", "x = a / b", "x = a & b", "x = a | b", "x = a ^ b", "x = a // b", "x = a * b + 1", "x = a + 1 * b", "x = a * b / c", "x = a * (1 + c)", "x, y, z = 1, 2, 3", "x = 'a' 'b' 'c'", "del foo", "del foo[bar]", "del foo.bar", "l[0]", "k[v,]", "m[a,b]", "a.b.c[d]", "file('some.txt').read()", "a[0].read()", "a[1:1].read()", "f('foo')('bar')('spam')", "f('foo')('bar')('spam').read()[0]", "a.b[0][0]", "a.b[0][:]", "a.b[0][::]", "a.b[0][0].pop()[0].push('bar')('baz').spam", "a.b[0].read()[1][2].foo().spam()[0].bar", "a**2", "a**2**2", "a.b[0]**2", "a.b[0].read()[1][2].foo().spam()[0].bar ** 2", "l[start:end] = l2", "l[::] = l2", "a = `s`", "a = `1 + 2 + f(3, 4)`", "[a, b] = c", "(a, b) = c", "[a, (b,c), d] = e", "a, (b, c), d = e", ] # We do not export the following tests because we would have to implement 2.5 # features in the stable compiler (other than just building the AST). expressions_inbetweenversions = expressions + [ "1 if True else 2", "1 if False else 2", ] funccalls = [ "l = func()", "l = func(10)", "l = func(10, 12, a, b=c, *args)", "l = func(10, 12, a, b=c, **kwargs)", "l = func(10, 12, a, b=c, *args, **kwargs)", "l = func(10, 12, a, b=c)", "e = l.pop(3)", "e = k.l.pop(3)", "simplefilter('ignore', category=PendingDeprecationWarning, append=1)", """methodmap = dict(subdirs=phase4, same_files=phase3, diff_files=phase3, funny_files=phase3, common_dirs = phase2, common_files=phase2, common_funny=phase2, common=phase1, left_only=phase1, right_only=phase1, left_list=phase0, right_list=phase0)""", "odata = b2a_qp(data, quotetabs = quotetabs, header = header)", ] listmakers = [ "l = []", "l = [1, 2, 3]", "l = [i for i in range(10)]", "l = [i for i in range(10) if i%2 == 0]", "l = [i for i in range(10) if i%2 == 0 or i%2 == 1]", # <-- "l = [i for i in range(10) if i%2 == 0 and i%2 == 1]", "l = [i for j in range(10) for i in range(j)]", "l = [i for j in range(10) for i in range(j) if j%2 == 0]", "l = [i for j in range(10) for i in range(j) if j%2 == 0 and i%2 == 0]", "l = [(a, b) for (a,b,c) in l2]", "l = [{a:b} for (a,b,c) in l2]", "l = [i for j in k if j%2 == 0 if j*2 < 20 for i in j if i%2==0]", ] genexps = [ "l = (i for i in j)", "l = (i for i in j if i%2 == 0)", "l = (i for j in k for i in j)", "l = (i for j in k for i in j if j%2==0)", "l = (i for j in k if j%2 == 0 if j*2 < 20 for i in j if i%2==0)", "l = (i for i in [ j*2 for j in range(10) ] )", "l = [i for i in ( j*2 for j in range(10) ) ]", "l = (i for i in [ j*2 for j in ( k*3 for k in range(10) ) ] )", "l = [i for j in ( j*2 for j in [ k*3 for k in range(10) ] ) ]", "l = f(i for i in j)", ] dictmakers = [ "l = {a : b, 'c' : 0}", "l = {}", ] backtrackings = [ "f = lambda x: x+1", "f = lambda x,y: x+y", "f = lambda x,y=1,z=t: x+y", "f = lambda x,y=1,z=t,*args,**kwargs: x+y", "f = lambda x,y=1,z=t,*args: x+y", "f = lambda x,y=1,z=t,**kwargs: x+y", "f = lambda: 1", "f = lambda *args: 1", "f = lambda **kwargs: 1", ] comparisons = [ "a < b", "a > b", "a not in b", "a is not b", "a in b", "a is b", "3 < x < 5", "(3 < x) < 5", "a < b < c < d", "(a < b) < (c < d)", "a < (b < c) < d", ] multiexpr = [ 'a = b; c = d;', 'a = b = c = d', ] attraccess = [ 'a.b = 2', 'x = a.b', ] slices = [ "l[:]", "l[::]", "l[1:2]", "l[1:]", "l[:2]", "l[1::]", "l[:1:]", "l[::1]", "l[1:2:]", "l[:1:2]", "l[1::2]", "l[0:1:2]", "a.b.l[:]", "a.b.l[1:2]", "a.b.l[1:]", "a.b.l[:2]", "a.b.l[0:1:2]", "a[1:2:3, 100]", "a[:2:3, 100]", "a[1::3, 100,]", "a[1:2:, 100]", "a[1:2, 100]", "a[1:, 100,]", "a[:2, 100]", "a[:, 100]", "a[100, 1:2:3,]", "a[100, :2:3]", "a[100, 1::3]", "a[100, 1:2:,]", "a[100, 1:2]", "a[100, 1:]", "a[100, :2,]", "a[100, :]", ] imports = [ 'import os', 'import sys, os', 'import os.path', 'import os.path, sys', 'import sys, os.path as osp', 'import os.path as osp', 'import os.path as osp, sys as _sys', 'import a.b.c.d', 'import a.b.c.d as abcd', 'from os import path', 'from os import path, system', ] imports_newstyle = [ 'from os import path, system', 'from os import path as P, system as S', 'from os import (path as P, system as S,)', 'from os import *', ] if_stmts = [ "if a == 1: a+= 2", """if a == 1: a += 2 elif a == 2: a += 3 else: a += 4 """, "if a and not b == c: pass", "if a and not not not b == c: pass", "if 0: print 'foo'" ] asserts = [ 'assert False', 'assert a == 1', 'assert a == 1 and b == 2', 'assert a == 1 and b == 2, "assertion failed"', ] execs = [ 'exec a', 'exec "a=b+3"', 'exec a in f()', 'exec a in f(), g()', ] prints = [ 'print', 'print a', 'print a,', 'print a, b', 'print a, "b", c', 'print >> err', 'print >> err, "error"', 'print >> err, "error",', 'print >> err, "error", a', ] globs = [ 'global a', 'global a,b,c', ] raises_ = [ # NB. 'raises' creates a name conflict with py.test magic 'raise', 'raise ValueError', 'raise ValueError("error")', 'raise ValueError, "error"', 'raise ValueError, "error", foo', ] tryexcepts = [ """try: a b except: pass """, """try: a b except NameError: pass """, """try: a b except NameError, err: pass """, """try: a b except (NameError, ValueError): pass """, """try: a b except (NameError, ValueError), err: pass """, """try: a except NameError, err: pass except ValueError, err: pass """, """def f(): try: a except NameError, err: a = 1 b = 2 except ValueError, err: a = 2 return a """ """try: a except NameError, err: a = 1 except ValueError, err: a = 2 else: a += 3 """, """try: a finally: b """, """def f(): try: return a finally: a = 3 return 1 """, ] one_stmt_funcdefs = [ "def f(): return 1", "def f(x): return x+1", "def f(x,y): return x+y", "def f(x,y=1,z=t): return x+y", "def f(x,y=1,z=t,*args,**kwargs): return x+y", "def f(x,y=1,z=t,*args): return x+y", "def f(x,y=1,z=t,**kwargs): return x+y", "def f(*args): return 1", "def f(**kwargs): return 1", "def f(t=()): pass", "def f(a, b, (c, d), e): pass", "def f(a, b, (c, (d, e), f, (g, h))): pass", "def f(a, b, (c, (d, e), f, (g, h)), i): pass", "def f((a)): pass", ] one_stmt_classdefs = [ "class Pdb(bdb.Bdb, cmd.Cmd): pass", ] docstrings = [ '''def foo(): return 1''', '''class Foo: pass''', '''class Foo: "foo"''', '''def foo(): """foo docstring""" return 1 ''', '''def foo(): """foo docstring""" a = 1 """bar""" return a ''', '''def foo(): """doc"""; print 1 a=1 ''', '''"""Docstring""";print 1''', ] returns = [ 'def f(): return', 'def f(): return 1', 'def f(): return a.b', 'def f(): return a', 'def f(): return a,b,c,d', #'return (a,b,c,d)', --- this one makes no sense, as far as I can tell ] augassigns = [ 'a=1;a+=2', 'a=1;a-=2', 'a=1;a*=2', 'a=1;a/=2', 'a=1;a//=2', 'a=1;a%=2', 'a=1;a**=2', 'a=1;a>>=2', 'a=1;a<<=2', 'a=1;a&=2', 'a=1;a^=2', 'a=1;a|=2', 'a=A();a.x+=2', 'a=A();a.x-=2', 'a=A();a.x*=2', 'a=A();a.x/=2', 'a=A();a.x//=2', 'a=A();a.x%=2', 'a=A();a.x**=2', 'a=A();a.x>>=2', 'a=A();a.x<<=2', 'a=A();a.x&=2', 'a=A();a.x^=2', 'a=A();a.x|=2', 'a=A();a[0]+=2', 'a=A();a[0]-=2', 'a=A();a[0]*=2', 'a=A();a[0]/=2', 'a=A();a[0]//=2', 'a=A();a[0]%=2', 'a=A();a[0]**=2', 'a=A();a[0]>>=2', 'a=A();a[0]<<=2', 'a=A();a[0]&=2', 'a=A();a[0]^=2', 'a=A();a[0]|=2', 'a=A();a[0:2]+=2', 'a=A();a[0:2]-=2', 'a=A();a[0:2]*=2', 'a=A();a[0:2]/=2', 'a=A();a[0:2]//=2', 'a=A();a[0:2]%=2', 'a=A();a[0:2]**=2', 'a=A();a[0:2]>>=2', 'a=A();a[0:2]<<=2', 'a=A();a[0:2]&=2', 'a=A();a[0:2]^=2', 'a=A();a[0:2]|=2', ] PY23_TESTS = [ constants, expressions, augassigns, comparisons, funccalls, backtrackings, listmakers, # ERRORS dictmakers, multiexpr, attraccess, slices, imports, execs, prints, globs, raises_, ] OPTIONAL_TESTS = [ # expressions_inbetweenversions, genexps, imports_newstyle, asserts, ] TESTS = PY23_TESTS + OPTIONAL_TESTS ## TESTS = [ ## ["l = [i for i in range(10) if i%2 == 0 or i%2 == 1]"], ## ] EXEC_INPUTS = [ one_stmt_classdefs, one_stmt_funcdefs, if_stmts, tryexcepts, docstrings, returns, ] SINGLE_INPUTS = [ one_stmt_funcdefs, ['\t # hello\n', 'print 6*7', 'if 1: x\n', 'x = 5', 'x = 5 ', '''"""Docstring""";print 1''', '''"Docstring"''', '''"Docstring" "\\x00"''', ] ]
Python
""" self cloning, automatic path configuration copy this into any subdirectory of pypy from which scripts need to be run, typically all of the test subdirs. The idea is that any such script simply issues import autopath and this will make sure that the parent directory containing "pypy" is in sys.path. If you modify the master "autopath.py" version (in pypy/tool/autopath.py) you can directly run it which will copy itself on all autopath.py files it finds under the pypy root directory. This module always provides these attributes: pypydir pypy root directory path this_dir directory where this autopath.py resides """ def __dirinfo(part): """ return (partdir, this_dir) and insert parent of partdir into sys.path. If the parent directories don't have the part an EnvironmentError is raised.""" import sys, os try: head = this_dir = os.path.realpath(os.path.dirname(__file__)) except NameError: head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0])) while head: partdir = head head, tail = os.path.split(head) if tail == part: break else: raise EnvironmentError, "'%s' missing in '%r'" % (partdir, this_dir) pypy_root = os.path.join(head, '') try: sys.path.remove(head) except ValueError: pass sys.path.insert(0, head) munged = {} for name, mod in sys.modules.items(): if '.' in name: continue fn = getattr(mod, '__file__', None) if not isinstance(fn, str): continue newname = os.path.splitext(os.path.basename(fn))[0] if not newname.startswith(part + '.'): continue path = os.path.join(os.path.dirname(os.path.realpath(fn)), '') if path.startswith(pypy_root) and newname != part: modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep) if newname != '__init__': modpaths.append(newname) modpath = '.'.join(modpaths) if modpath not in sys.modules: munged[modpath] = mod for name, mod in munged.iteritems(): if name not in sys.modules: sys.modules[name] = mod if '.' in name: prename = name[:name.rfind('.')] postname = name[len(prename)+1:] if prename not in sys.modules: __import__(prename) if not hasattr(sys.modules[prename], postname): setattr(sys.modules[prename], postname, mod) return partdir, this_dir def __clone(): """ clone master version of autopath.py into all subdirs """ from os.path import join, walk if not this_dir.endswith(join('pypy','tool')): raise EnvironmentError("can only clone master version " "'%s'" % join(pypydir, 'tool',_myname)) def sync_walker(arg, dirname, fnames): if _myname in fnames: fn = join(dirname, _myname) f = open(fn, 'rwb+') try: if f.read() == arg: print "checkok", fn else: print "syncing", fn f = open(fn, 'w') f.write(arg) finally: f.close() s = open(join(pypydir, 'tool', _myname), 'rb').read() walk(pypydir, sync_walker, s) _myname = 'autopath.py' # set guaranteed attributes pypydir, this_dir = __dirinfo('pypy') if __name__ == '__main__': __clone()
Python
# EXPECT: Module(None, Stmt([From('__future__', [('with_statement', None)]), With(Name('acontext'), Stmt([Pass()]), None)])) from __future__ import with_statement with acontext: pass
Python
# -*- coding: ISO-8859-1 -*- a = 1 # keep this statement for now (see test_only_one_comment.py)
Python
print >> f
Python
# coding: ISO-8859-1 # encoding on the third line <=> no encoding a = 1
Python
class A: def with_white_spaces_before(self): pass def another_method(self, foo): bar = foo class B(object, A): def foo(self, bar): a = 2 return "spam"
Python
[i for i in range(10) if i%2 == 0] # same list on several lines [i for i in range(10) if i%2 == 0] [i for i in 1,2] [(i,j) for i in 1,2 for j in 3,4]
Python
import os import os.path as osp from sets import Set, ImmutableSet
Python
class A: def with_white_spaces_before(self): pass def another_method(self, foo): """with a docstring on several lines # with a sharpsign """ self.bar = foo
Python
#!/usr/bin/env python # coding: ISO_LATIN_1 a = 1
Python
# EXPECT: Module(None, Stmt([From('__future__', [('with_statement', None)]), With(Name('acontext'), Stmt([Pass()]), AssName('avariable', OP_ASSIGN))])) from __future__ import with_statement with acontext as avariable: pass
Python
for x in range(10): pass for x in range(5): a += x b += 2 if False: break else: continue else: c = 3 for index, val in enumerate(range(5)): val *= 2
Python
l = [ "foo", "bar", "baz"] l = [ "foo", "bar", "baz", ] l = [] l = [ ]
Python
a[1:]
Python
f() f(a) f(a,) f(a,b) f(a, b,) f(*args) f(**kwargs) f(*args, **kwargs) f(a, *args, **kwargs) f(a, b, *args, **kwargs) a = 1
Python
while (a < b and c < d and e < f): pass while (a < b and c < d and e < f): pass while (a < b and c < d and e < f): pass while (a < b and c < d and e < f): pass
Python
x = 1
Python
l = [] l . append ( 12 )
Python
"""module docstring""" """hello """ class A: """class doctring on several lines """ def foo(self): """function docstring""" def boo(x): """Docstring""";print 1 """world"""
Python
L = [] print L[0:10] def f(): print 1 # commentaire foireux x = 1 s = "asd" class A: def f(): pass
Python
# Function(Decorators([Name('foo')]), 'f', ['a', 'b'], [], 0, None, Stmt([Pass()])) @foo def f(a, b): pass @accepts(int, (int,float)) @returns((int,float)) def func0(arg1, arg2): return arg1 * arg2 ## Stmt([Function(Decorators([CallFunc(Getattr(Getattr(Name('mod1'), 'mod2'), 'accepts'), [Name('int'), Tuple([Name('int'), Name('float')])], None, None), ## CallFunc(Getattr(Getattr(Name('mod1'), 'mod2'), 'returns'), [Tuple([Name('int'), Name('float')])], None, None)]), ## 'func', ['arg1', 'arg2'], [], 0, None, Stmt([Return(Mul((Name('arg1'), Name('arg2'))))]))]) @mod1.mod2.accepts(int, (int,float)) @mod1.mod2.returns((int,float)) def func(arg1, arg2): return arg1 * arg2
Python
index = 0 while index < 10: index += 1 foo = 10 - index if False: break else: foo = 12
Python
try: a b except: pass try: a b except NameError: pass try: a b except NameError, err: pass try: a b except (NameError, ValueError): pass try: a b except (NameError, ValueError), err: pass try: a except NameError, err: pass except ValueError, err: pass try: a except NameError, err: pass except ValueError, err: pass else: pass try: a finally: b
Python
#!/usr/bin/env python # coding: ISO_LATIN_1 a = 1
Python
def f(n): for i in range(n): yield n
Python
# only one comment
Python
x = 0x1L # comment a = 1 # yo # hello # world a = 2 # end
Python
x in range(10)
Python
from foo import bar, \ baz if True and \ False \ and True: print "excellent !"
Python
def f(a, b=1, *args, **kwargs): if args: a += len(args) if kwargs: a += len(kwargs) return a*b
Python
a = 1 a = -1 a = 1. a = .2 a = 1.2 a = 1e3 a = 1.3e4 a = -1.3
Python
x = y + 1
Python
"""This module does nothing""";print 1
Python
a = 1 b = 2 c = a + b
Python
import os, os.path as osp import sys from ebnf import parse_grammar from python import python_parse, pypy_parse, set_debug from pprint import pprint import grammar grammar.DEBUG = False from symbol import sym_name def name(elt): return "%s[%d]"% (sym_name.get(elt,elt),elt) def read_samples_dir(): return [osp.join('samples', fname) for fname in os.listdir('samples') if fname.endswith('.py')] def print_sym_tuple( tup ): print "\n(", for elt in tup: if type(elt)==int: print name(elt), elif type(elt)==str: print repr(elt), else: print_sym_tuple(elt) print ")", def assert_tuples_equal(tup1, tup2, curpos = (), disp=""): if disp: print "\n"+disp+"(", for index, (elt1, elt2) in enumerate(zip(tup1, tup2)): if disp and elt1==elt2 and type(elt1)==int: print name(elt1), if elt1 != elt2: if type(elt1) is tuple and type(elt2) is tuple: if disp: disp=disp+" " assert_tuples_equal(elt1, elt2, curpos + (index,), disp) print print "TUP1" print_sym_tuple(tup1) print print "TUP2" print_sym_tuple(tup2) raise AssertionError('Found difference at %s : %s != %s' % (curpos, name(elt1), name(elt2) ), curpos) if disp: print ")", def test_samples( samples ): for sample in samples: pypy_tuples = pypy_parse(sample) python_tuples = python_parse(sample) print "="*20 print file(sample).read() print "-"*10 pprint(pypy_tuples) print "-"*10 pprint(python_tuples) try: assert_tuples_equal( python_tuples, pypy_tuples, disp=" " ) assert python_tuples == pypy_tuples except AssertionError,e: print print "python_tuples" show( python_tuples, e.args[-1] ) print print "pypy_tuples" show( pypy_tuples, e.args[-1] ) raise def show( tup, idxs ): for level, i in enumerate(idxs): print " "*level , tup tup=tup[i] print tup if __name__=="__main__": import getopt opts, args = getopt.getopt( sys.argv[1:], "d:", [] ) for opt, val in opts: if opt=="-d": set_debug(int(val)) if args: samples = args else: samples = read_samples_dir() test_samples( samples )
Python
a is not None
Python
a[1:]
Python
from pypy.interpreter import error from pypy.interpreter import baseobjspace, module, main import sys import code import time class Completer: """ Stolen mostly from CPython's rlcompleter.py """ def __init__(self, space, w_globals): self.space = space self.w_globals = w_globals def complete(self, text, state): if state == 0: if "." in text: self.matches = self.attr_matches(text) else: self.matches = self.global_matches(text) try: return self.matches[state] except IndexError: return None def global_matches(self, text): import keyword w_res = self.space.call_method(self.w_globals, "keys") namespace_keys = self.space.unwrap(w_res) w_res = self.space.call_method(self.space.builtin.getdict(), "keys") builtin_keys = self.space.unwrap(w_res) matches = [] n = len(text) for l in [namespace_keys, builtin_keys, keyword.kwlist]: for word in l: if word[:n] == text and word != "__builtins__": matches.append(word) return matches def attr_matches(self, text): import re m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) if not m: return expr, attr = m.group(1, 3) s = self.space w_obj = s.eval(expr, self.w_globals, self.w_globals) words = self.get_words(w_obj) w_clz = s.getattr(w_obj, s.wrap("__class__")) words += self.get_class_members(w_clz) matches = [] n = len(attr) for word in words: if word[:n] == attr and word != "__builtins__": matches.append("%s.%s" % (expr, word)) return matches def get_words(self, w_clz): s = self.space w_dir_func = s.builtin.get("dir") w_res = s.call_function(w_dir_func, w_clz) return s.unwrap(w_res) def get_class_members(self, w_clz): s = self.space words = self.get_words(w_clz) try: w_bases = s.getattr(w_clz, s.wrap("__bases__")) bases_w = s.unpacktuple(w_bases) except error.OperationError: return words for w_clz in bases_w: words += self.get_class_members(w_clz) return words class PyPyConsole(code.InteractiveConsole): def __init__(self, objspace, verbose=0, completer=False): code.InteractiveConsole.__init__(self) self.space = objspace self.verbose = verbose space = self.space self.console_compiler_flags = 0 mainmodule = main.ensure__main__(space) self.w_globals = mainmodule.w_dict space.setitem(self.w_globals, space.wrap('__builtins__'), space.builtin) if completer: self.enable_command_line_completer() # forbidden: #space.exec_("__pytrace__ = 0", self.w_globals, self.w_globals) space.setitem(self.w_globals, space.wrap('__pytrace__'),space.wrap(0)) self.tracelevel = 0 self.console_locals = {} def enable_command_line_completer(self): try: import readline # Keep here to save windoze tears readline.set_completer(Completer(self.space, self.w_globals).complete) readline.parse_and_bind("tab: complete") readline.set_history_length(25000) try: readline.read_history_file() except IOError: pass # guess it doesn't exit import atexit atexit.register(readline.write_history_file) except: pass def interact(self, banner=None): #banner = "Python %s in pypy\n%s / %s" % ( # sys.version, self.__class__.__name__, # self.space.__class__.__name__) w_sys = self.space.sys major, minor, micro, _, _ = self.space.unwrap(self.space.sys.get('pypy_version_info')) elapsed = time.time() - self.space._starttime banner = "PyPy %d.%d.%d in %r on top of Python %s (startuptime: %.2f secs)" % ( major, minor, micro, self.space, sys.version.split()[0], elapsed) code.InteractiveConsole.interact(self, banner) def raw_input(self, prompt=""): # add a character to the PyPy prompt so that you know where you # are when you debug it with "python -i py.py" try: return code.InteractiveConsole.raw_input(self, prompt[0] + prompt) except KeyboardInterrupt: # fires into an interpreter-level console print banner = ("Python %s on %s\n" % (sys.version, sys.platform) + "*** Entering interpreter-level console ***") local = self.console_locals # don't copy attributes that look like names that came # from self.w_globals (itself the main offender) as they # would then get copied back into the applevel namespace. local.update(dict([(k,v) for (k, v) in self.__dict__.iteritems() if not k.startswith('w_')])) del local['locals'] for w_name in self.space.unpackiterable(self.w_globals): local['w_' + self.space.str_w(w_name)] = ( self.space.getitem(self.w_globals, w_name)) code.interact(banner=banner, local=local) # copy back 'w_' names for name in local: if name.startswith('w_'): self.space.setitem(self.w_globals, self.space.wrap(name[2:]), local[name]) print '*** Leaving interpreter-level console ***' raise def runcode(self, code): raise NotImplementedError def runsource(self, source, ignored_filename="<input>", symbol="single"): # the following hacked file name is recognized specially by error.py hacked_filename = '<inline>\n' + source compiler = self.space.getexecutioncontext().compiler def doit(): # compile the provided input code = compiler.compile_command(source, hacked_filename, symbol, self.console_compiler_flags) if code is None: raise IncompleteInput self.console_compiler_flags |= compiler.getcodeflags(code) # execute it self.settrace() try: code.exec_code(self.space, self.w_globals, self.w_globals) finally: if self.tracelevel: self.space.unsettrace() self.checktrace() # run doit() in an exception-catching box try: main.run_toplevel(self.space, doit, verbose=self.verbose) except IncompleteInput: return 1 else: return 0 def settrace(self): if self.tracelevel: self.space.settrace() def checktrace(self): from pypy.objspace import trace s = self.space # Did we modify __pytrace__ tracelevel = s.int_w(s.getitem(self.w_globals, s.wrap("__pytrace__"))) if self.tracelevel > 0 and tracelevel == 0: s.reset_trace() print "Tracing disabled" if self.tracelevel == 0 and tracelevel > 0: trace.create_trace_space(s) self.space.unsettrace() print "Tracing enabled" self.tracelevel = tracelevel class IncompleteInput(Exception): pass
Python
""" Module objects. """ from pypy.interpreter.baseobjspace import Wrappable class Module(Wrappable): """A module.""" def __init__(self, space, w_name, w_dict=None): self.space = space if w_dict is None: w_dict = space.newdict(track_builtin_shadowing=True) self.w_dict = w_dict self.w_name = w_name if w_name is not None: space.setitem(w_dict, space.new_interned_str('__name__'), w_name) def setup_after_space_initialization(self): """NOT_RPYTHON: to allow built-in modules to do some more setup after the space is fully initialized.""" def startup(self, space): """This is called at runtime before the space gets uses to allow the module to do initialization at runtime. """ def getdict(self): return self.w_dict def descr_module__new__(space, w_subtype, __args__): module = space.allocate_instance(Module, w_subtype) Module.__init__(module, space, None) return space.wrap(module) def descr_module__init__(self, w_name, w_doc=None): space = self.space self.w_name = w_name if w_doc is None: w_doc = space.w_None space.setitem(self.w_dict, space.new_interned_str('__name__'), w_name) space.setitem(self.w_dict, space.new_interned_str('__doc__'), w_doc) def descr__reduce__(self, space): w_name = space.finditem(self.w_dict, space.wrap('__name__')) if (w_name is None or not space.is_true(space.isinstance(w_name, space.w_str))): # maybe raise exception here (XXX this path is untested) return space.w_None w_modules = space.sys.get('modules') if space.finditem(w_modules, w_name) is None: #not imported case from pypy.interpreter.mixedmodule import MixedModule w_mod = space.getbuiltinmodule('_pickle_support') mod = space.interp_w(MixedModule, w_mod) new_inst = mod.get('module_new') return space.newtuple([new_inst, space.newtuple([w_name, self.getdict()]), ]) #already imported case w_import = space.builtin.get('__import__') return space.newtuple([w_import, space.newtuple([w_name])])
Python
""" This module defines the abstract base classes that support execution: Code and Frame. """ from pypy.interpreter.error import OperationError from pypy.interpreter.baseobjspace import Wrappable from pypy.rlib import rstack # for resume points class Code(Wrappable): """A code is a compiled version of some source code. Abstract base class.""" hidden_applevel = False def __init__(self, co_name): self.co_name = co_name def exec_code(self, space, w_globals, w_locals): "Implements the 'exec' statement." # this should be on PyCode? frame = space.createframe(self, w_globals, None) frame.setdictscope(w_locals) return frame.run() def signature(self): "([list-of-arg-names], vararg-name-or-None, kwarg-name-or-None)." return [], None, None def getvarnames(self): """List of names including the arguments, vararg and kwarg, and possibly more locals.""" argnames, varargname, kwargname = self.signature() if varargname is not None: argnames = argnames + [varargname] if kwargname is not None: argnames = argnames + [kwargname] return argnames def getformalargcount(self): argnames, varargname, kwargname = self.signature() argcount = len(argnames) if varargname is not None: argcount += 1 if kwargname is not None: argcount += 1 return argcount def getdocstring(self, space): return space.w_None def funcrun(self, func, args): frame = func.space.createframe(self, func.w_func_globals, func.closure) sig = self.signature() scope_w = args.parse(func.name, sig, func.defs_w) frame.setfastscope(scope_w) return frame.run() # a performance hack (see gateway.BuiltinCode1/2/3 and pycode.PyCode) def fastcall_0(self, space, func): return None def fastcall_1(self, space, func, w1): return None def fastcall_2(self, space, func, w1, w2): return None def fastcall_3(self, space, func, w1, w2, w3): return None def fastcall_4(self, space, func, w1, w2, w3, w4): return None class Frame(Wrappable): """A frame is an environment supporting the execution of a code object. Abstract base class.""" def __init__(self, space, w_globals=None, numlocals=-1): self.space = space self.w_globals = w_globals # wrapped dict of globals self.w_locals = None # wrapped dict of locals if numlocals < 0: # compute the minimal size based on arguments numlocals = len(self.getcode().getvarnames()) self.numlocals = numlocals def run(self): "Abstract method to override. Runs the frame" raise TypeError, "abstract" def getdictscope(self): "Get the locals as a dictionary." self.fast2locals() return self.w_locals def getcode(self): return None def fget_code(space, self): return space.wrap(self.getcode()) def fget_getdictscope(space, self): # unwrapping through unwrap_spec in typedef.py return self.getdictscope() def setdictscope(self, w_locals): "Initialize the locals from a dictionary." self.w_locals = w_locals self.locals2fast() def getfastscope(self): "Abstract. Get the fast locals as a list." raise TypeError, "abstract" def setfastscope(self, scope_w): """Abstract. Initialize the fast locals from a list of values, where the order is according to self.getcode().signature().""" raise TypeError, "abstract" def fast2locals(self): # Copy values from self.fastlocals_w to self.w_locals if self.w_locals is None: self.w_locals = self.space.newdict() varnames = self.getcode().getvarnames() fastscope_w = self.getfastscope() for i in range(min(len(varnames), len(fastscope_w))): name = varnames[i] w_value = fastscope_w[i] if w_value is not None: w_name = self.space.wrap(name) self.space.setitem(self.w_locals, w_name, w_value) def locals2fast(self): # Copy values from self.w_locals to self.fastlocals_w assert self.w_locals is not None varnames = self.getcode().getvarnames() new_fastlocals_w = [None]*self.numlocals for i in range(min(len(varnames), self.numlocals)): w_name = self.space.wrap(varnames[i]) try: w_value = self.space.getitem(self.w_locals, w_name) except OperationError, e: if not e.match(self.space, self.space.w_KeyError): raise else: new_fastlocals_w[i] = w_value self.setfastscope(new_fastlocals_w)
Python
""" Two bytecodes to speed up method calls. Here is how a method call looks like: (on the left, without the new bytecodes; on the right, with them) <push self> <push self> LOAD_ATTR name LOOKUP_METHOD name <push arg 0> <push arg 0> ... ... <push arg n-1> <push arg n-1> CALL_FUNCTION n CALL_METHOD n """ from pypy.interpreter import pyframe, function from pypy.rlib.jit import we_are_jitted from pypy.interpreter.argument import Arguments def object_getattribute(space): w_src, w_getattribute = space.lookup_in_type_where(space.w_object, '__getattribute__') return w_getattribute object_getattribute._annspecialcase_ = 'specialize:memo' class __extend__(pyframe.PyFrame): def LOOKUP_METHOD(f, nameindex, *ignored): # stack before after # -------------- --fast-method----fallback-case------------ # # w_object None # w_object => w_function w_boundmethod_or_whatever # (more stuff) (more stuff) (more stuff) # # NB. this assumes a space based on pypy.objspace.descroperation. space = f.space w_obj = f.popvalue() w_name = f.getname_w(nameindex) w_value = None w_getattribute = space.lookup(w_obj, '__getattribute__') if w_getattribute is object_getattribute(space): name = space.str_w(w_name) w_descr = space.lookup(w_obj, name) if w_descr is None: # this handles directly the common case # module.function(args..) w_value = w_obj.getdictvalue(space, w_name) elif type(w_descr) is function.Function: w_value = w_obj.getdictvalue_attr_is_in_class(space, w_name) if w_value is None: # fast method path: a function object in the class, # nothing in the instance f.pushvalue(w_descr) f.pushvalue(w_obj) return if w_value is None: w_value = space.getattr(w_obj, w_name) f.pushvalue(w_value) f.pushvalue(None) def CALL_METHOD(f, nargs, *ignored): # 'nargs' is the argument count excluding the implicit 'self' w_self = f.peekvalue(nargs) w_callable = f.peekvalue(nargs + 1) n = nargs + (w_self is not None) try: w_result = f.space.call_valuestack(w_callable, n, f) finally: f.dropvalues(nargs + 2) f.pushvalue(w_result)
Python
w_foo2 = space.wrap("hello") foo2 = "never mind" # should be hidden by w_foo2 def foobuilder(w_name): name = space.unwrap(w_name) return space.wrap("hi, %s!" % name) from __applevel__ import bar fortytwo = bar(space.wrap(6), space.wrap(7))
Python
### a trivial program to test strings, lists, functions and methods ### ## tiny change wrt goal so far needed: explicit parameter to str.split def addstr(s1,s2): return s1 + s2 str = "an interesting string" str2 = 'another::string::xxx::y:aa' str3 = addstr(str,str2) arr = [] for word in str.split(' '): if word in str2.split('::'): arr.append(word) print ''.join(arr) print "str + str2 = ", str3
Python
def somefunc(space): return space.w_True def initpath(space): print "got to initpath", space return space.wrap(3)
Python
from pypy.interpreter.mixedmodule import MixedModule class Module(MixedModule): interpleveldefs = { '__name__' : '(space.wrap("mixedmodule"))', '__doc__' : '(space.wrap("mixedmodule doc"))', 'somefunc' : 'file1.somefunc', 'value' : '(space.w_None)', 'path' : 'file1.initpath(space)', 'cpypath' : 'space.wrap(sys.path)' } appleveldefs = { 'someappfunc' : 'file2_app.someappfunc', }
Python
def someappfunc(x): return x + 1
Python
def main(aStr): print len(aStr) map(main, ["hello world", "good bye"]) apply(main, ("apply works, too",)) apply(main, (), {"aStr": "it really works"}) print chr(65)
Python
""" A custom graphic renderer for the '.plain' files produced by dot. """ from __future__ import generators import re, os, math import pygame from pygame.locals import * this_dir = os.path.dirname(os.path.abspath(__file__)) FONT = os.path.join(this_dir, 'cyrvetic.ttf') FIXEDFONT = os.path.join(this_dir, 'VeraMoBd.ttf') COLOR = { 'black': (0,0,0), 'white': (255,255,255), 'red': (255,0,0), 'green': (0,255,0), 'blue': (0,0,255), 'yellow': (255,255,0), } re_nonword=re.compile(r'([^0-9a-zA-Z_.]+)') def combine(color1, color2, alpha): r1, g1, b1 = color1 r2, g2, b2 = color2 beta = 1.0 - alpha return (int(r1 * alpha + r2 * beta), int(g1 * alpha + g2 * beta), int(b1 * alpha + b2 * beta)) def highlight_color(color): if color == (0, 0, 0): # black becomes magenta return (255, 0, 255) elif color == (255, 255, 255): # white becomes yellow return (255, 255, 0) intensity = sum(color) if intensity > 191 * 3: return combine(color, (128, 192, 0), 0.2) else: return combine(color, (255, 255, 0), 0.2) def getcolor(name, default): if name in COLOR: return COLOR[name] elif name.startswith('#') and len(name) == 7: rval = COLOR[name] = (int(name[1:3],16), int(name[3:5],16), int(name[5:7],16)) return rval else: return default class GraphLayout: fixedfont = False def __init__(self, scale, width, height): self.scale = scale self.boundingbox = width, height self.nodes = {} self.edges = [] self.links = {} def add_node(self, *args): n = Node(*args) self.nodes[n.name] = n def add_edge(self, *args): self.edges.append(Edge(self.nodes, *args)) def get_display(self): from graphdisplay import GraphDisplay return GraphDisplay(self) def display(self): self.get_display().run() def reload(self): return self # async interaction helpers def display_async_quit(): pygame.event.post(pygame.event.Event(QUIT)) def display_async_cmd(**kwds): pygame.event.post(pygame.event.Event(USEREVENT, **kwds)) EventQueue = [] def wait_for_events(): if not EventQueue: EventQueue.append(pygame.event.wait()) EventQueue.extend(pygame.event.get()) def wait_for_async_cmd(): # wait until another thread pushes a USEREVENT in the queue while True: wait_for_events() e = EventQueue.pop(0) if e.type in (USEREVENT, QUIT): # discard all other events break EventQueue.insert(0, e) # re-insert the event for further processing class Node: def __init__(self, name, x, y, w, h, label, style, shape, color, fillcolor): self.name = name self.x = float(x) self.y = float(y) self.w = float(w) self.h = float(h) self.label = label self.style = style self.shape = shape self.color = color self.fillcolor = fillcolor self.highlight = False def sethighlight(self, which): self.highlight = bool(which) class Edge: label = None def __init__(self, nodes, tail, head, cnt, *rest): self.tail = nodes[tail] self.head = nodes[head] cnt = int(cnt) self.points = [(float(rest[i]), float(rest[i+1])) for i in range(0, cnt*2, 2)] rest = rest[cnt*2:] if len(rest) > 2: self.label, xl, yl = rest[:3] self.xl = float(xl) self.yl = float(yl) rest = rest[3:] self.style, self.color = rest self.highlight = False self.cachedbezierpoints = None self.cachedarrowhead = None self.cachedlimits = None def sethighlight(self, which): self.highlight = bool(which) def limits(self): result = self.cachedlimits if result is None: points = self.bezierpoints() xs = [point[0] for point in points] ys = [point[1] for point in points] self.cachedlimits = result = (min(xs), max(ys), max(xs), min(ys)) return result def bezierpoints(self): result = self.cachedbezierpoints if result is None: result = [] pts = self.points for i in range(0, len(pts)-3, 3): result += beziercurve(pts[i], pts[i+1], pts[i+2], pts[i+3]) self.cachedbezierpoints = result return result def arrowhead(self): result = self.cachedarrowhead if result is None: bottom_up = self.points[0][1] > self.points[-1][1] if (self.tail.y > self.head.y) != bottom_up: # reversed edge head = 0 dir = 1 else: head = -1 dir = -1 n = 1 while True: try: x0, y0 = self.points[head] x1, y1 = self.points[head+n*dir] except IndexError: result = [] break vx = x0-x1 vy = y0-y1 try: f = 0.12 / math.sqrt(vx*vx + vy*vy) vx *= f vy *= f result = [(x0 + 0.9*vx, y0 + 0.9*vy), (x0 + 0.4*vy, y0 - 0.4*vx), (x0 - 0.4*vy, y0 + 0.4*vx)] break except (ZeroDivisionError, ValueError): n += 1 self.cachedarrowhead = result return result def beziercurve((x0,y0), (x1,y1), (x2,y2), (x3,y3), resolution=8): result = [] f = 1.0/(resolution-1) append = result.append for i in range(resolution): t = f*i t0 = (1-t)*(1-t)*(1-t) t1 = t *(1-t)*(1-t) * 3.0 t2 = t * t *(1-t) * 3.0 t3 = t * t * t append((x0*t0 + x1*t1 + x2*t2 + x3*t3, y0*t0 + y1*t1 + y2*t2 + y3*t3)) return result def segmentdistance((x0,y0), (x1,y1), (x,y)): "Distance between the point (x,y) and the segment (x0,y0)-(x1,y1)." vx = x1-x0 vy = y1-y0 try: l = math.hypot(vx, vy) vx /= l vy /= l dlong = vx*(x-x0) + vy*(y-y0) except (ZeroDivisionError, ValueError): dlong = -1 if dlong < 0.0: return math.hypot(x-x0, y-y0) elif dlong > l: return math.hypot(x-x1, y-y1) else: return abs(vy*(x-x0) - vx*(y-y0)) class GraphRenderer: MARGIN = 0.6 SCALEMIN = 3 SCALEMAX = 100 FONTCACHE = {} def __init__(self, screen, graphlayout, scale=75): self.graphlayout = graphlayout self.setscale(scale) self.setoffset(0, 0) self.screen = screen self.textzones = [] self.highlightwords = graphlayout.links self.highlight_word = None self.visiblenodes = [] self.visibleedges = [] def wordcolor(self, word): info = self.highlightwords[word] if isinstance(info, tuple) and len(info) >= 2: color = info[1] else: color = None if color is None: color = (128,0,0) if word == self.highlight_word: return ((255,255,80), color) else: return (color, None) def setscale(self, scale): scale = max(min(scale, self.SCALEMAX), self.SCALEMIN) self.scale = float(scale) w, h = self.graphlayout.boundingbox self.margin = int(self.MARGIN * scale) self.width = int(w * scale) + (2 * self.margin) self.height = int(h * scale) + (2 * self.margin) self.bboxh = h size = int(15 * (scale-10) / 75) self.font = self.getfont(size) def getfont(self, size): if size in self.FONTCACHE: return self.FONTCACHE[size] elif size < 5: self.FONTCACHE[size] = None return None else: if self.graphlayout.fixedfont: filename = FIXEDFONT else: filename = FONT font = self.FONTCACHE[size] = pygame.font.Font(filename, size) return font def setoffset(self, offsetx, offsety): "Set the (x,y) origin of the rectangle where the graph will be rendered." self.ofsx = offsetx - self.margin self.ofsy = offsety - self.margin def shiftoffset(self, dx, dy): self.ofsx += dx self.ofsy += dy def getcenter(self): w, h = self.screen.get_size() return self.revmap(w//2, h//2) def setcenter(self, x, y): w, h = self.screen.get_size() x, y = self.map(x, y) self.shiftoffset(x-w//2, y-h//2) def shiftscale(self, factor, fix=None): if fix is None: fixx, fixy = self.screen.get_size() fixx //= 2 fixy //= 2 else: fixx, fixy = fix x, y = self.revmap(fixx, fixy) self.setscale(self.scale * factor) newx, newy = self.map(x, y) self.shiftoffset(newx - fixx, newy - fixy) def reoffset(self, swidth, sheight): offsetx = noffsetx = self.ofsx offsety = noffsety = self.ofsy width = self.width height = self.height # if it fits, center it, otherwise clamp if width <= swidth: noffsetx = (width - swidth) // 2 else: noffsetx = min(max(0, offsetx), width - swidth) if height <= sheight: noffsety = (height - sheight) // 2 else: noffsety = min(max(0, offsety), height - sheight) self.ofsx = noffsetx self.ofsy = noffsety def getboundingbox(self): "Get the rectangle where the graph will be rendered." return (-self.ofsx, -self.ofsy, self.width, self.height) def visible(self, x1, y1, x2, y2): """Is any part of the box visible (i.e. within the bounding box)? We have to perform clipping ourselves because with big graphs the coordinates may sometimes become longs and cause OverflowErrors within pygame. """ w, h = self.screen.get_size() return x1 < w and x2 > 0 and y1 < h and y2 > 0 def computevisible(self): del self.visiblenodes[:] del self.visibleedges[:] w, h = self.screen.get_size() for node in self.graphlayout.nodes.values(): x, y = self.map(node.x, node.y) nw2 = int(node.w * self.scale)//2 nh2 = int(node.h * self.scale)//2 if x-nw2 < w and x+nw2 > 0 and y-nh2 < h and y+nh2 > 0: self.visiblenodes.append(node) for edge in self.graphlayout.edges: x1, y1, x2, y2 = edge.limits() x1, y1 = self.map(x1, y1) if x1 < w and y1 < h: x2, y2 = self.map(x2, y2) if x2 > 0 and y2 > 0: self.visibleedges.append(edge) def map(self, x, y): return (int(x*self.scale) - (self.ofsx - self.margin), int((self.bboxh-y)*self.scale) - (self.ofsy - self.margin)) def revmap(self, px, py): return ((px + (self.ofsx - self.margin)) / self.scale, self.bboxh - (py + (self.ofsy - self.margin)) / self.scale) def draw_node_commands(self, node): xcenter, ycenter = self.map(node.x, node.y) boxwidth = int(node.w * self.scale) boxheight = int(node.h * self.scale) fgcolor = getcolor(node.color, (0,0,0)) bgcolor = getcolor(node.fillcolor, (255,255,255)) if node.highlight: fgcolor = highlight_color(fgcolor) bgcolor = highlight_color(bgcolor) text = node.label lines = text.replace('\\l','\\l\n').replace('\r','\r\n').split('\n') # ignore a final newline if not lines[-1]: del lines[-1] wmax = 0 hmax = 0 commands = [] bkgndcommands = [] if self.font is None: if lines: raw_line = lines[0].replace('\\l','').replace('\r','') if raw_line: for size in (12, 10, 8, 6, 4): font = self.getfont(size) img = TextSnippet(self, raw_line, (0, 0, 0), bgcolor, font=font) w, h = img.get_size() if (w >= boxwidth or h >= boxheight): continue else: if w>wmax: wmax = w def cmd(img=img, y=hmax, w=w): img.draw(xcenter-w//2, ytop+y) commands.append(cmd) hmax += h break else: for line in lines: raw_line = line.replace('\\l','').replace('\r','') or ' ' img = TextSnippet(self, raw_line, (0, 0, 0), bgcolor) w, h = img.get_size() if w>wmax: wmax = w if raw_line.strip(): if line.endswith('\\l'): def cmd(img=img, y=hmax): img.draw(xleft, ytop+y) elif line.endswith('\r'): def cmd(img=img, y=hmax, w=w): img.draw(xright-w, ytop+y) else: def cmd(img=img, y=hmax, w=w): img.draw(xcenter-w//2, ytop+y) commands.append(cmd) hmax += h #hmax += 8 # we know the bounding box only now; setting these variables will # have an effect on the values seen inside the cmd() functions above xleft = xcenter - wmax//2 xright = xcenter + wmax//2 ytop = ycenter - hmax//2 x = xcenter-boxwidth//2 y = ycenter-boxheight//2 if node.shape == 'box': rect = (x-1, y-1, boxwidth+2, boxheight+2) def cmd(): self.screen.fill(bgcolor, rect) bkgndcommands.append(cmd) def cmd(): pygame.draw.rect(self.screen, fgcolor, rect, 1) commands.append(cmd) elif node.shape == 'ellipse': rect = (x-1, y-1, boxwidth+2, boxheight+2) def cmd(): pygame.draw.ellipse(self.screen, bgcolor, rect, 0) bkgndcommands.append(cmd) def cmd(): pygame.draw.ellipse(self.screen, fgcolor, rect, 1) commands.append(cmd) elif node.shape == 'octagon': step = 1-math.sqrt(2)/2 points = [(int(x+boxwidth*fx), int(y+boxheight*fy)) for fx, fy in [(step,0), (1-step,0), (1,step), (1,1-step), (1-step,1), (step,1), (0,1-step), (0,step)]] def cmd(): pygame.draw.polygon(self.screen, bgcolor, points, 0) bkgndcommands.append(cmd) def cmd(): pygame.draw.polygon(self.screen, fgcolor, points, 1) commands.append(cmd) return bkgndcommands, commands def draw_commands(self): nodebkgndcmd = [] nodecmd = [] for node in self.visiblenodes: cmd1, cmd2 = self.draw_node_commands(node) nodebkgndcmd += cmd1 nodecmd += cmd2 edgebodycmd = [] edgeheadcmd = [] for edge in self.visibleedges: fgcolor = getcolor(edge.color, (0,0,0)) if edge.highlight: fgcolor = highlight_color(fgcolor) points = [self.map(*xy) for xy in edge.bezierpoints()] def drawedgebody(points=points, fgcolor=fgcolor): pygame.draw.lines(self.screen, fgcolor, False, points) edgebodycmd.append(drawedgebody) points = [self.map(*xy) for xy in edge.arrowhead()] if points: def drawedgehead(points=points, fgcolor=fgcolor): pygame.draw.polygon(self.screen, fgcolor, points, 0) edgeheadcmd.append(drawedgehead) if edge.label: x, y = self.map(edge.xl, edge.yl) img = TextSnippet(self, edge.label, (0, 0, 0)) w, h = img.get_size() if self.visible(x-w//2, y-h//2, x+w//2, y+h//2): def drawedgelabel(img=img, x1=x-w//2, y1=y-h//2): img.draw(x1, y1) edgeheadcmd.append(drawedgelabel) return edgebodycmd + nodebkgndcmd + edgeheadcmd + nodecmd def render(self): self.computevisible() bbox = self.getboundingbox() ox, oy, width, height = bbox dpy_width, dpy_height = self.screen.get_size() # some versions of the SDL misinterpret widely out-of-range values, # so clamp them if ox < 0: width += ox ox = 0 if oy < 0: height += oy oy = 0 if width > dpy_width: width = dpy_width if height > dpy_height: height = dpy_height self.screen.fill((224, 255, 224), (ox, oy, width, height)) # gray off-bkgnd areas gray = (128, 128, 128) if ox > 0: self.screen.fill(gray, (0, 0, ox, dpy_height)) if oy > 0: self.screen.fill(gray, (0, 0, dpy_width, oy)) w = dpy_width - (ox + width) if w > 0: self.screen.fill(gray, (dpy_width-w, 0, w, dpy_height)) h = dpy_height - (oy + height) if h > 0: self.screen.fill(gray, (0, dpy_height-h, dpy_width, h)) # draw the graph and record the position of texts del self.textzones[:] for cmd in self.draw_commands(): cmd() def findall(self, searchstr): """Return an iterator for all nodes and edges that contain a searchstr. """ for item in self.graphlayout.nodes.itervalues(): if item.label and searchstr in item.label: yield item for item in self.graphlayout.edges: if item.label and searchstr in item.label: yield item def at_position(self, (x, y)): """Figure out the word under the cursor.""" for rx, ry, rw, rh, word in self.textzones: if rx <= x < rx+rw and ry <= y < ry+rh: return word return None def node_at_position(self, (x, y)): """Return the Node under the cursor.""" x, y = self.revmap(x, y) for node in self.visiblenodes: if 2.0*abs(x-node.x) <= node.w and 2.0*abs(y-node.y) <= node.h: return node return None def edge_at_position(self, (x, y), distmax=14): """Return the Edge near the cursor.""" # XXX this function is very CPU-intensive and makes the display kinda sluggish distmax /= self.scale xy = self.revmap(x, y) closest_edge = None for edge in self.visibleedges: pts = edge.bezierpoints() for i in range(1, len(pts)): d = segmentdistance(pts[i-1], pts[i], xy) if d < distmax: distmax = d closest_edge = edge return closest_edge class TextSnippet: def __init__(self, renderer, text, fgcolor, bgcolor=None, font=None): self.renderer = renderer self.imgs = [] self.parts = [] if font is None: font = renderer.font if font is None: return parts = self.parts for word in re_nonword.split(text): if not word: continue if word in renderer.highlightwords: fg, bg = renderer.wordcolor(word) bg = bg or bgcolor else: fg, bg = fgcolor, bgcolor parts.append((word, fg, bg)) # consolidate sequences of words with the same color for i in range(len(parts)-2, -1, -1): if parts[i][1:] == parts[i+1][1:]: word, fg, bg = parts[i] parts[i] = word + parts[i+1][0], fg, bg del parts[i+1] # delete None backgrounds for i in range(len(parts)): if parts[i][2] is None: parts[i] = parts[i][:2] # render parts i = 0 while i < len(parts): part = parts[i] word = part[0] try: try: img = font.render(word, False, *part[1:]) except pygame.error, e: # Try *with* anti-aliasing to work around a bug in SDL img = font.render(word, True, *part[1:]) except pygame.error: del parts[i] # Text has zero width else: self.imgs.append(img) i += 1 def get_size(self): if self.imgs: sizes = [img.get_size() for img in self.imgs] return sum([w for w,h in sizes]), max([h for w,h in sizes]) else: return 0, 0 def draw(self, x, y): for part, img in zip(self.parts, self.imgs): word = part[0] self.renderer.screen.blit(img, (x, y)) w, h = img.get_size() self.renderer.textzones.append((x, y, w, h, word)) x += w try: sum # 2.3 only except NameError: def sum(lst): total = 0 for item in lst: total += lst return total
Python
#! /usr/bin/env python """ Usage: graphserver.py <port number> Start a server listening for connexions on the given port. """ import sys import msgstruct from cStringIO import StringIO class Server(object): def __init__(self, io): self.io = io self.display = None def run(self, only_one_graph=False): # wait for the CMSG_INIT message msg = self.io.recvmsg() if msg[0] != msgstruct.CMSG_INIT or msg[1] != msgstruct.MAGIC: raise ValueError("bad MAGIC number") # process messages until we have a pygame display while self.display is None: self.process_next_message() # start a background thread to process further messages if not only_one_graph: import thread thread.start_new_thread(self.process_all_messages, ()) # give control to pygame self.display.run1() def process_all_messages(self): try: while True: self.process_next_message() except EOFError: from drawgraph import display_async_quit display_async_quit() def process_next_message(self): msg = self.io.recvmsg() fn = self.MESSAGES.get(msg[0]) if fn: fn(self, *msg[1:]) else: self.log("unknown message code %r" % (msg[0],)) def log(self, info): print >> sys.stderr, info def setlayout(self, layout): if self.display is None: # make the initial display from graphdisplay import GraphDisplay self.display = GraphDisplay(layout) else: # send an async command to the display running the main thread from drawgraph import display_async_cmd display_async_cmd(layout=layout) def cmsg_start_graph(self, graph_id, scale, width, height, *rest): from drawgraph import GraphLayout self.newlayout = GraphLayout(float(scale), float(width), float(height)) def request_reload(): self.io.sendmsg(msgstruct.MSG_RELOAD, graph_id) def request_followlink(word): self.io.sendmsg(msgstruct.MSG_FOLLOW_LINK, graph_id, word) self.newlayout.request_reload = request_reload self.newlayout.request_followlink = request_followlink def cmsg_add_node(self, *args): self.newlayout.add_node(*args) def cmsg_add_edge(self, *args): self.newlayout.add_edge(*args) def cmsg_add_link(self, word, *info): if len(info) == 1: info = info[0] elif len(info) >= 4: info = (info[0], info[1:4]) self.newlayout.links[word] = info def cmsg_fixed_font(self, *rest): self.newlayout.fixedfont = True def cmsg_stop_graph(self, *rest): self.setlayout(self.newlayout) del self.newlayout self.io.sendmsg(msgstruct.MSG_OK) def cmsg_missing_link(self, *rest): self.setlayout(None) def cmsg_say(self, errmsg, *rest): from drawgraph import display_async_cmd display_async_cmd(say=errmsg) MESSAGES = { msgstruct.CMSG_START_GRAPH: cmsg_start_graph, msgstruct.CMSG_ADD_NODE: cmsg_add_node, msgstruct.CMSG_ADD_EDGE: cmsg_add_edge, msgstruct.CMSG_ADD_LINK: cmsg_add_link, msgstruct.CMSG_FIXED_FONT: cmsg_fixed_font, msgstruct.CMSG_STOP_GRAPH: cmsg_stop_graph, msgstruct.CMSG_MISSING_LINK:cmsg_missing_link, msgstruct.CMSG_SAY: cmsg_say, } def listen_server(local_address): import socket, graphclient, thread if isinstance(local_address, str): if ':' in local_address: interface, port = local_address.split(':') else: interface, port = '', local_address local_address = interface, int(port) s1 = socket.socket() s1.bind(local_address) s1.listen(5) print 'listening on %r...' % (s1.getsockname(),) while True: conn, addr = s1.accept() print 'accepted connexion from %r' % (addr,) sock_io = msgstruct.SocketIO(conn) handler_io = graphclient.spawn_local_handler() thread.start_new_thread(copy_all, (sock_io, handler_io)) thread.start_new_thread(copy_all, (handler_io, sock_io)) del sock_io, handler_io, conn def copy_all(io1, io2): try: while True: io2.sendall(io1.recv()) except EOFError: io2.close_sending() if __name__ == '__main__': if len(sys.argv) != 2: print >> sys.stderr, __doc__ sys.exit(2) if sys.argv[1] == '--stdio': # a one-shot server running on stdin/stdout io = msgstruct.FileIO(sys.stdin, sys.stdout) srv = Server(io) try: srv.run() except Exception, e: import traceback f = StringIO() traceback.print_exc(file=f) # try to add some explanations help = (" | if you want to debug on a remote machine, set the\n" " | GRAPHSERVER env var to a HOSTNAME:PORT pointing\n" " | back to a locally running graphserver.py.") try: import pygame except ImportError: f.seek(0) f.truncate() print >> f, "ImportError" print >> f, " | Pygame is not installed; either install it, or" print >> f, help else: if isinstance(e, pygame.error): print >> f, help io.sendmsg(msgstruct.MSG_ERROR, f.getvalue()) else: listen_server(sys.argv[1])
Python
import sys, os from struct import pack, unpack, calcsize MAGIC = -0x3b83728b CMSG_INIT = 'i' CMSG_START_GRAPH = '[' CMSG_ADD_NODE = 'n' CMSG_ADD_EDGE = 'e' CMSG_ADD_LINK = 'l' CMSG_FIXED_FONT = 'f' CMSG_STOP_GRAPH = ']' CMSG_MISSING_LINK= 'm' CMSG_SAY = 's' MSG_OK = 'O' MSG_ERROR = 'E' MSG_RELOAD = 'R' MSG_FOLLOW_LINK = 'L' # ____________________________________________________________ long_min = -2147483648 long_max = 2147483647 def message(tp, *values): #print >> sys.stderr, tp, values typecodes = [''] for v in values: if type(v) is str: typecodes.append('%ds' % len(v)) elif 0 <= v < 256: typecodes.append('B') elif long_min <= v <= long_max: typecodes.append('l') else: typecodes.append('q') typecodes = ''.join(typecodes) if len(typecodes) < 256: return pack(("!B%dsc" % len(typecodes)) + typecodes, len(typecodes), typecodes, tp, *values) else: # too many values - encapsulate the message in another one return message('\x00', typecodes, pack("!c" + typecodes, tp, *values)) def decodemessage(data): if data: limit = ord(data[0]) + 1 if len(data) >= limit: typecodes = "!c" + data[1:limit] end = limit + calcsize(typecodes) if len(data) >= end: msg = unpack(typecodes, data[limit:end]) if msg[0] == '\x00': msg = unpack("!c" + msg[1], msg[2]) return msg, data[end:] #elif end > 1000000: # raise OverflowError return None, data # ____________________________________________________________ class RemoteError(Exception): pass class IO(object): _buffer = '' def sendmsg(self, tp, *values): self.sendall(message(tp, *values)) def recvmsg(self): while True: msg, self._buffer = decodemessage(self._buffer) if msg is not None: break self._buffer += self.recv() if msg[0] != MSG_ERROR: return msg raise RemoteError(*msg[1:]) class FileIO(IO): def __init__(self, f_in, f_out): if sys.platform == 'win32': import msvcrt msvcrt.setmode(f_in.fileno(), os.O_BINARY) msvcrt.setmode(f_out.fileno(), os.O_BINARY) self.f_in = f_in self.f_out = f_out def sendall(self, data): self.f_out.write(data) def recv(self): fd = self.f_in.fileno() data = os.read(fd, 16384) if not data: raise EOFError return data def close_sending(self): self.f_out.close() def close(self): self.f_out.close() self.f_in.close() class SocketIO(IO): def __init__(self, s): self.s = s def sendall(self, data): self.s.sendall(data) def recv(self): data = self.s.recv(16384) if not data: raise EOFError return data def close_sending(self): self.s.shutdown(1) # SHUT_WR def close(self): self.s.close()
Python
import py Option = py.test.config.Option option = py.test.config.addoptions("dotviewer options", Option('--pygame', action="store_true", dest="pygame", default=False, help="allow interactive tests using Pygame"), )
Python
#! /usr/bin/env python """ Command-line interface for a dot file viewer. dotviewer.py filename.dot dotviewer.py filename.plain dotviewer.py --server [interface:]port In the first form, show the graph contained in a .dot file. In the second form, the graph was already compiled to a .plain file. In the third form, listen for connexion on the given port and display the graphs sent by the remote side. On the remote site, set the GRAPHSERVER environment variable to HOST:PORT. """ import sys def main(args = sys.argv[1:]): import getopt options, args = getopt.getopt(args, 's:h', ['server=', 'help']) server_addr = None for option, value in options: if option in ('-h', '--help'): print >> sys.stderr, __doc__ sys.exit(2) if option in ('-s', '--server'): server_addr = value if not args and server_addr is None: print >> sys.stderr, __doc__ sys.exit(2) for filename in args: import graphclient graphclient.display_dot_file(filename) if server_addr is not None: import graphserver graphserver.listen_server(server_addr) if __name__ == '__main__': main()
Python
#! /usr/bin/env python """ Usage: graphserver.py <port number> Start a server listening for connexions on the given port. """ import sys import msgstruct from cStringIO import StringIO class Server(object): def __init__(self, io): self.io = io self.display = None def run(self, only_one_graph=False): # wait for the CMSG_INIT message msg = self.io.recvmsg() if msg[0] != msgstruct.CMSG_INIT or msg[1] != msgstruct.MAGIC: raise ValueError("bad MAGIC number") # process messages until we have a pygame display while self.display is None: self.process_next_message() # start a background thread to process further messages if not only_one_graph: import thread thread.start_new_thread(self.process_all_messages, ()) # give control to pygame self.display.run1() def process_all_messages(self): try: while True: self.process_next_message() except EOFError: from drawgraph import display_async_quit display_async_quit() def process_next_message(self): msg = self.io.recvmsg() fn = self.MESSAGES.get(msg[0]) if fn: fn(self, *msg[1:]) else: self.log("unknown message code %r" % (msg[0],)) def log(self, info): print >> sys.stderr, info def setlayout(self, layout): if self.display is None: # make the initial display from graphdisplay import GraphDisplay self.display = GraphDisplay(layout) else: # send an async command to the display running the main thread from drawgraph import display_async_cmd display_async_cmd(layout=layout) def cmsg_start_graph(self, graph_id, scale, width, height, *rest): from drawgraph import GraphLayout self.newlayout = GraphLayout(float(scale), float(width), float(height)) def request_reload(): self.io.sendmsg(msgstruct.MSG_RELOAD, graph_id) def request_followlink(word): self.io.sendmsg(msgstruct.MSG_FOLLOW_LINK, graph_id, word) self.newlayout.request_reload = request_reload self.newlayout.request_followlink = request_followlink def cmsg_add_node(self, *args): self.newlayout.add_node(*args) def cmsg_add_edge(self, *args): self.newlayout.add_edge(*args) def cmsg_add_link(self, word, *info): if len(info) == 1: info = info[0] elif len(info) >= 4: info = (info[0], info[1:4]) self.newlayout.links[word] = info def cmsg_fixed_font(self, *rest): self.newlayout.fixedfont = True def cmsg_stop_graph(self, *rest): self.setlayout(self.newlayout) del self.newlayout self.io.sendmsg(msgstruct.MSG_OK) def cmsg_missing_link(self, *rest): self.setlayout(None) def cmsg_say(self, errmsg, *rest): from drawgraph import display_async_cmd display_async_cmd(say=errmsg) MESSAGES = { msgstruct.CMSG_START_GRAPH: cmsg_start_graph, msgstruct.CMSG_ADD_NODE: cmsg_add_node, msgstruct.CMSG_ADD_EDGE: cmsg_add_edge, msgstruct.CMSG_ADD_LINK: cmsg_add_link, msgstruct.CMSG_FIXED_FONT: cmsg_fixed_font, msgstruct.CMSG_STOP_GRAPH: cmsg_stop_graph, msgstruct.CMSG_MISSING_LINK:cmsg_missing_link, msgstruct.CMSG_SAY: cmsg_say, } def listen_server(local_address): import socket, graphclient, thread if isinstance(local_address, str): if ':' in local_address: interface, port = local_address.split(':') else: interface, port = '', local_address local_address = interface, int(port) s1 = socket.socket() s1.bind(local_address) s1.listen(5) print 'listening on %r...' % (s1.getsockname(),) while True: conn, addr = s1.accept() print 'accepted connexion from %r' % (addr,) sock_io = msgstruct.SocketIO(conn) handler_io = graphclient.spawn_local_handler() thread.start_new_thread(copy_all, (sock_io, handler_io)) thread.start_new_thread(copy_all, (handler_io, sock_io)) del sock_io, handler_io, conn def copy_all(io1, io2): try: while True: io2.sendall(io1.recv()) except EOFError: io2.close_sending() if __name__ == '__main__': if len(sys.argv) != 2: print >> sys.stderr, __doc__ sys.exit(2) if sys.argv[1] == '--stdio': # a one-shot server running on stdin/stdout io = msgstruct.FileIO(sys.stdin, sys.stdout) srv = Server(io) try: srv.run() except Exception, e: import traceback f = StringIO() traceback.print_exc(file=f) # try to add some explanations help = (" | if you want to debug on a remote machine, set the\n" " | GRAPHSERVER env var to a HOSTNAME:PORT pointing\n" " | back to a locally running graphserver.py.") try: import pygame except ImportError: f.seek(0) f.truncate() print >> f, "ImportError" print >> f, " | Pygame is not installed; either install it, or" print >> f, help else: if isinstance(e, pygame.error): print >> f, help io.sendmsg(msgstruct.MSG_ERROR, f.getvalue()) else: listen_server(sys.argv[1])
Python
import os, sys, re import msgstruct this_dir = os.path.dirname(os.path.abspath(__file__)) GRAPHSERVER = os.path.join(this_dir, 'graphserver.py') def display_dot_file(dotfile, wait=True, save_tmp_file=None): """ Display the given dot file in a subprocess. """ if not os.path.exists(str(dotfile)): raise IOError("No such file: %s" % (dotfile,)) import graphpage page = graphpage.DotFileGraphPage(str(dotfile)) display_page(page, wait=wait, save_tmp_file=save_tmp_file) def display_page(page, wait=True, save_tmp_file=None): messages = [(msgstruct.CMSG_INIT, msgstruct.MAGIC)] history = [page] pagecache = {} def getpage(graph_id): page = history[graph_id] try: return pagecache[page] except KeyError: result = page.content() pagecache.clear() # a cache of a single entry should be enough pagecache[page] = result return result def reload(graph_id): page = getpage(graph_id) if save_tmp_file: f = open(save_tmp_file, 'w') f.write(page.source) f.close() messages.extend(page_messages(page, graph_id)) send_graph_messages(io, messages) del messages[:] io = spawn_handler() reload(0) if wait: try: while True: msg = io.recvmsg() # handle server-side messages if msg[0] == msgstruct.MSG_RELOAD: graph_id = msg[1] pagecache.clear() reload(graph_id) elif msg[0] == msgstruct.MSG_FOLLOW_LINK: graph_id = msg[1] word = msg[2] page = getpage(graph_id) try: page = page.followlink(word) except KeyError: io.sendmsg(msgstruct.CMSG_MISSING_LINK) else: # when following a link from an older page, assume that # we can drop the more recent history graph_id += 1 history[graph_id:] = [page] reload(graph_id) except EOFError: pass except Exception, e: send_error(io, e) raise io.close() def page_messages(page, graph_id): import graphparse return graphparse.parse_dot(graph_id, page.source, page.links, getattr(page, 'fixedfont', False)) def send_graph_messages(io, messages): ioerror = None for msg in messages: try: io.sendmsg(*msg) except IOError, ioerror: break # wait for MSG_OK or MSG_ERROR try: while True: msg = io.recvmsg() if msg[0] == msgstruct.MSG_OK: break except EOFError: ioerror = ioerror or IOError("connexion unexpectedly closed " "(graphserver crash?)") if ioerror is not None: raise ioerror def send_error(io, e): try: errmsg = str(e) if errmsg: errmsg = '%s: %s' % (e.__class__.__name__, errmsg) else: errmsg = '%s' % (e.__class__.__name__,) io.sendmsg(msgstruct.CMSG_SAY, errmsg) except Exception: pass def spawn_handler(): gsvar = os.environ.get('GRAPHSERVER') if not gsvar: return spawn_local_handler() else: try: host, port = gsvar.split(':') host = host or '127.0.0.1' port = int(port) except ValueError: raise ValueError("$GRAPHSERVER must be set to HOST:PORT, got %r" % (gvvar,)) import socket s = socket.socket() s.connect((host, port)) return msgstruct.SocketIO(s) def spawn_local_handler(): if hasattr(sys, 'pypy_objspaceclass'): python = 'python' else: python = sys.executable cmdline = '"%s" -u "%s" --stdio' % (python, GRAPHSERVER) child_in, child_out = os.popen2(cmdline, 'tb', 0) io = msgstruct.FileIO(child_out, child_in) return io
Python
from __future__ import generators import os, time, sys import pygame from pygame.locals import * from drawgraph import GraphRenderer, FIXEDFONT from drawgraph import Node, Edge from drawgraph import EventQueue, wait_for_events METAKEYS = dict([ (ident[len('KMOD_'):].lower(), getattr(pygame.locals, ident)) for ident in dir(pygame.locals) if ident.startswith('KMOD_') and ident != 'KMOD_NONE' ]) if sys.platform == 'darwin': PMETA = 'lmeta', 'rmeta' else: PMETA = 'lalt', 'ralt', 'lctrl', 'rctrl' METAKEYS['meta'] = PMETA METAKEYS['shift'] = 'lshift', 'rshift' KEYS = dict([ (ident[len('K_'):].lower(), getattr(pygame.locals, ident)) for ident in dir(pygame.locals) if ident.startswith('K_') ]) KEYS['plus'] = ('=', '+', '.') KEYS['quit'] = ('q', 'escape') KEYS['help'] = ('h', '?', 'f1') def GET_KEY(key): if len(key) == 1: return key return KEYS[key] def permute_mods(base, args): if not args: yield base return first, rest = args[0], args[1:] for val in first: for rval in permute_mods(base | val, rest): yield rval class Display(object): def __init__(self, (w,h)=(800,680)): # initialize the modules by hand, to avoid initializing too much # (e.g. the sound system) pygame.display.init() pygame.font.init() self.resize((w,h)) def resize(self, (w,h)): self.width = w self.height = h self.screen = pygame.display.set_mode((w, h), HWSURFACE|RESIZABLE, 32) class GraphDisplay(Display): STATUSBARFONT = FIXEDFONT ANIM_STEP = 0.03 KEY_REPEAT = (500, 30) STATUSBAR_ALPHA = 0.75 STATUSBAR_FGCOLOR = (255, 255, 80) STATUSBAR_BGCOLOR = (128, 0, 0) STATUSBAR_OVERFLOWCOLOR = (255, 0, 0) HELP_ALPHA = 0.95 HELP_FGCOLOR = (255, 255, 80) HELP_BGCOLOR = (0, 128, 0) INPUT_ALPHA = 0.75 INPUT_FGCOLOR = (255, 255, 80) INPUT_BGCOLOR = (0, 0, 128) KEYS = { 'meta -' : ('zoom', 0.5), '-' : ('zoom', 0.5), 'meta plus' : ('zoom', 2.0), 'plus' : ('zoom', 2.0), 'meta 0' : 'zoom_actual_size', '0' : 'zoom_actual_size', 'meta 1' : 'zoom_to_fit', '1' : 'zoom_to_fit', 'meta f4' : 'quit', 'meta quit' : 'quit', 'quit' : 'quit', 'meta right' : 'layout_forward', 'meta left': 'layout_back', 'backspace' : 'layout_back', 'f': 'search', '/': 'search', 'n': 'find_next', 'p': 'find_prev', 'r': 'reload', 'left' : ('pan', (-1, 0)), 'right' : ('pan', (1, 0)), 'up' : ('pan', (0, -1)), 'down' : ('pan', (0, 1)), 'shift left' : ('fast_pan', (-1, 0)), 'shift right' : ('fast_pan', (1, 0)), 'shift up' : ('fast_pan', (0, -1)), 'shift down' : ('fast_pan', (0, 1)), 'help': 'help', 'space': 'hit', } HELP_MSG = """ Key bindings: +, = or . Zoom in - Zoom out 1 Zoom to fit 0 Actual size Arrows Scroll Shift+Arrows Scroll faster Space Follow word link Backspace Go back in history Meta Left Go back in history Meta Right Go forward in history R Reload the page F or / Search for text N Find next occurrence P Find previous occurrence F1, H or ? This help message Q or Esc Quit Mouse bindings: Click on objects to move around Drag with the left mouse button to zoom in/out Drag with the right mouse button to scroll """.replace('\n ', '\n').strip() # poor man's dedent def __init__(self, layout): super(GraphDisplay, self).__init__() self.font = pygame.font.Font(self.STATUSBARFONT, 16) self.viewers_history = [] self.forward_viewers_history = [] self.highlight_word = None self.highlight_obj = None self.viewer = None self.method_cache = {} self.key_cache = {} self.ascii_key_cache = {} self.status_bar_height = 0 self.searchstr = None self.searchpos = 0 self.searchresults = [] self.initialize_keys() self.setlayout(layout) def initialize_keys(self): pygame.key.set_repeat(*self.KEY_REPEAT) mask = 0 for strnames, methodname in self.KEYS.iteritems(): names = strnames.split() if not isinstance(methodname, basestring): methodname, args = methodname[0], methodname[1:] else: args = () method = getattr(self, methodname, None) if method is None: print 'Can not implement key mapping %r, %s.%s does not exist' % ( strnames, self.__class__.__name__, methodname) continue mods = [] basemod = 0 keys = [] for name in names: if name in METAKEYS: val = METAKEYS[name] if not isinstance(val, int): mods.append(tuple([METAKEYS[k] for k in val])) else: basemod |= val else: val = GET_KEY(name) assert len(keys) == 0 if not isinstance(val, (int, basestring)): keys.extend([GET_KEY(k) for k in val]) else: keys.append(val) assert keys for key in keys: if isinstance(key, int): for mod in permute_mods(basemod, mods): self.key_cache[(key, mod)] = (method, args) mask |= mod else: for mod in permute_mods(basemod, mods): char = key.lower() mod = mod & ~KMOD_SHIFT self.ascii_key_cache[(char, mod)] = (method, args) mask |= mod self.key_mask = mask def help(self): """Show a help window and wait for a key or a mouse press.""" margin_x = margin_y = 64 padding_x = padding_y = 8 fgcolor = self.HELP_FGCOLOR bgcolor = self.HELP_BGCOLOR helpmsg = self.HELP_MSG width = self.width - 2*margin_x height = self.height - 2*margin_y lines = rendertext(helpmsg, self.font, fgcolor, width - 2*padding_x, height - 2*padding_y) block = pygame.Surface((width, height), SWSURFACE | SRCALPHA) block.fill(bgcolor) sx = padding_x sy = padding_y for img in lines: w, h = img.get_size() block.blit(img, (sx, sy)) sy += h block.set_alpha(int(255 * self.HELP_ALPHA)) self.screen.blit(block, (margin_x, margin_y)) pygame.display.flip() while True: wait_for_events() e = EventQueue.pop(0) if e.type in (MOUSEBUTTONDOWN, KEYDOWN, QUIT): break if e.type == QUIT: EventQueue.insert(0, e) # re-insert a QUIT self.must_redraw = True def input(self, prompt): """Ask the user to input something. Returns the string that the user entered, or None if the user pressed Esc. """ def draw(text): margin_x = margin_y = 0 padding_x = padding_y = 8 fgcolor = self.INPUT_FGCOLOR bgcolor = self.INPUT_BGCOLOR width = self.width - 2*margin_x lines = renderline(text, self.font, fgcolor, width - 2*padding_x) height = totalheight(lines) + 2 * padding_y block = pygame.Surface((width, height), SWSURFACE | SRCALPHA) block.fill(bgcolor) sx = padding_x sy = padding_y for img in lines: w, h = img.get_size() block.blit(img, (sx, sy)) sy += h block.set_alpha(int(255 * self.INPUT_ALPHA)) # This can be slow. It would be better to take a screenshot # and use it as the background. self.viewer.render() if self.statusbarinfo: self.drawstatusbar() self.screen.blit(block, (margin_x, margin_y)) pygame.display.flip() draw(prompt) text = "" self.must_redraw = True while True: wait_for_events() old_text = text events = EventQueue[:] del EventQueue[:] for e in events: if e.type == QUIT: EventQueue.insert(0, e) # re-insert a QUIT return None elif e.type == KEYDOWN: if e.key == K_ESCAPE: return None elif e.key == K_RETURN: return text.encode('latin-1') # XXX do better elif e.key == K_BACKSPACE: text = text[:-1] elif e.unicode and ord(e.unicode) >= ord(' '): text += e.unicode if text != old_text: draw(prompt + text) def hit(self): word = self.highlight_word if word is not None: if word in self.layout.links: self.setstatusbar('loading...') self.redraw_now() self.layout.request_followlink(word) def search(self): searchstr = self.input('Find: ') if not searchstr: return self.searchstr = searchstr self.searchpos = -1 self.searchresults = list(self.viewer.findall(self.searchstr)) self.find_next() def find_next(self): if not self.searchstr: return if self.searchpos + 1 >= len(self.searchresults): self.setstatusbar('Not found: %s' % self.searchstr) return self.searchpos += 1 self.highlight_found_item() def find_prev(self): if not self.searchstr: return if self.searchpos - 1 < 0: self.setstatusbar('Not found: %s' % self.searchstr) return self.searchpos -= 1 self.highlight_found_item() def highlight_found_item(self): item = self.searchresults[self.searchpos] self.sethighlight(obj=item) msg = 'Found %%s containing %s (%d/%d)' % ( self.searchstr.replace('%', '%%'), self.searchpos+1, len(self.searchresults)) if isinstance(item, Node): self.setstatusbar(msg % 'node') self.look_at_node(item, keep_highlight=True) elif isinstance(item, Edge): self.setstatusbar(msg % 'edge') self.look_at_edge(item, keep_highlight=True) else: # should never happen self.setstatusbar(msg % item) def setlayout(self, layout): if self.viewer and getattr(self.viewer.graphlayout, 'key', True) is not None: self.viewers_history.append(self.viewer) del self.forward_viewers_history[:] self.layout = layout self.viewer = GraphRenderer(self.screen, layout) self.searchpos = 0 self.searchresults = [] self.zoom_to_fit() def zoom_actual_size(self): self.viewer.shiftscale(float(self.viewer.SCALEMAX) / self.viewer.scale) self.updated_viewer() def calculate_zoom_to_fit(self): return min(float(self.width) / self.viewer.width, float(self.height) / self.viewer.height, float(self.viewer.SCALEMAX) / self.viewer.scale) def zoom_to_fit(self): """ center and scale to view the whole graph """ f = self.calculate_zoom_to_fit() self.viewer.shiftscale(f) self.updated_viewer() def zoom(self, scale): self.viewer.shiftscale(max(scale, self.calculate_zoom_to_fit())) self.updated_viewer() def reoffset(self): self.viewer.reoffset(self.width, self.height) def pan(self, (x, y)): self.viewer.shiftoffset(x * (self.width // 8), y * (self.height // 8)) self.updated_viewer() def fast_pan(self, (x, y)): self.pan((x * 4, y * 4)) def update_status_bar(self): self.statusbarinfo = None self.must_redraw = True if self.viewers_history: info = 'Press Backspace to go back to previous screen' else: info = 'Press H for help' self.setstatusbar(info) def updated_viewer(self, keep_highlight=False): self.reoffset() if not keep_highlight: self.sethighlight() self.update_status_bar() self.must_redraw = True def layout_back(self): if self.viewers_history: self.forward_viewers_history.append(self.viewer) self.viewer = self.viewers_history.pop() self.layout = self.viewer.graphlayout self.updated_viewer() def layout_forward(self): if self.forward_viewers_history: self.viewers_history.append(self.viewer) self.viewer = self.forward_viewers_history.pop() self.layout = self.viewer.graphlayout self.updated_viewer() def reload(self): self.setstatusbar('reloading...') self.redraw_now() self.layout.request_reload() def setstatusbar(self, text, fgcolor=None, bgcolor=None): info = (text, fgcolor or self.STATUSBAR_FGCOLOR, bgcolor or self.STATUSBAR_BGCOLOR) if info != self.statusbarinfo: self.statusbarinfo = info self.must_redraw = True def drawstatusbar(self): text, fgcolor, bgcolor = self.statusbarinfo maxheight = self.height / 2 lines = rendertext(text, self.font, fgcolor, self.width, maxheight, self.STATUSBAR_OVERFLOWCOLOR) totalh = totalheight(lines) y = self.height - totalh self.status_bar_height = totalh + 16 block = pygame.Surface((self.width, self.status_bar_height), SWSURFACE | SRCALPHA) block.fill(bgcolor) sy = 16 for img in lines: w, h = img.get_size() block.blit(img, ((self.width-w)//2, sy-8)) sy += h block.set_alpha(int(255 * self.STATUSBAR_ALPHA)) self.screen.blit(block, (0, y-16)) def notifymousepos(self, pos): word = self.viewer.at_position(pos) if word in self.layout.links: info = self.layout.links[word] if isinstance(info, tuple): info = info[0] self.setstatusbar(info) self.sethighlight(word) return node = self.viewer.node_at_position(pos) if node: self.setstatusbar(shortlabel(node.label)) self.sethighlight(obj=node) return edge = self.viewer.edge_at_position(pos) if edge: info = '%s -> %s' % (shortlabel(edge.tail.label), shortlabel(edge.head.label)) if edge.label: info += '\n' + shortlabel(edge.label) self.setstatusbar(info) self.sethighlight(obj=edge) return self.sethighlight() def notifyclick(self, pos): word = self.viewer.at_position(pos) if word in self.layout.links: self.setstatusbar('loading...') self.redraw_now() self.layout.request_followlink(word) return node = self.viewer.node_at_position(pos) if node: self.look_at_node(node) else: edge = self.viewer.edge_at_position(pos) if edge: if (self.distance_to_node(edge.head) >= self.distance_to_node(edge.tail)): self.look_at_node(edge.head) else: self.look_at_node(edge.tail) def sethighlight(self, word=None, obj=None): if word == self.highlight_word and obj is self.highlight_obj: return # Nothing has changed, so there's no need to redraw self.viewer.highlight_word = word if self.highlight_obj is not None: self.highlight_obj.sethighlight(False) if obj is not None: obj.sethighlight(True) self.highlight_word = word self.highlight_obj = obj self.must_redraw = True def animation(self, expectedtime=0.6): start = time.time() step = 0.0 n = 0 while True: step += self.ANIM_STEP if step >= expectedtime: break yield step / expectedtime n += 1 now = time.time() frametime = (now-start) / n self.ANIM_STEP = self.ANIM_STEP * 0.9 + frametime * 0.1 yield 1.0 def distance_to_node(self, node): cx1, cy1 = self.viewer.getcenter() cx2, cy2 = node.x, node.y return (cx2-cx1)*(cx2-cx1) + (cy2-cy1)*(cy2-cy1) def look_at_node(self, node, keep_highlight=False): """Shift the node in view.""" self.look_at(node.x, node.y, node.w, node.h, keep_highlight) def look_at_edge(self, edge, keep_highlight=False): """Shift the edge's label into view.""" points = edge.bezierpoints() xmin = min([x for (x, y) in points]) xmax = max([x for (x, y) in points]) ymin = min([y for (x, y) in points]) ymax = max([y for (x, y) in points]) x = (xmin + xmax) / 2 y = (ymin + ymax) / 2 w = max(1, xmax - xmin) h = max(1, ymax - ymin) self.look_at(x, y, w, h, keep_highlight) def look_at(self, targetx, targety, targetw, targeth, keep_highlight=False): """Shift the node in view.""" endscale = min(float(self.width-40) / targetw, float(self.height-40) / targeth, 75) startscale = self.viewer.scale cx1, cy1 = self.viewer.getcenter() cx2, cy2 = targetx, targety moving = (abs(startscale-endscale) + abs(cx1-cx2) + abs(cy1-cy2) > 0.4) if moving: # if the target is far off the window, reduce scale along the way tx, ty = self.viewer.map(cx2, cy2) offview = max(-tx, -ty, tx-self.width, ty-self.height) middlescale = endscale * (0.999 ** offview) if offview > 150 and middlescale < startscale: bumpscale = 4.0 * (middlescale - 0.5*(startscale+endscale)) else: bumpscale = 0.0 if not keep_highlight: self.statusbarinfo = None self.sethighlight() for t in self.animation(): self.viewer.setscale(startscale*(1-t) + endscale*t + bumpscale*t*(1-t)) self.viewer.setcenter(cx1*(1-t) + cx2*t, cy1*(1-t) + cy2*t) self.updated_viewer(keep_highlight=keep_highlight) self.redraw_now() return moving def peek(self, typ): for event in EventQueue: if event.type == typ: return True return False def process_event(self, event): method = self.method_cache.get(event.type, KeyError) if method is KeyError: method = getattr(self, 'process_%s' % (pygame.event.event_name(event.type),), None) self.method_cache[method] = method if method is not None: method(event) def process_MouseMotion(self, event): if self.peek(MOUSEMOTION): return if self.dragging: if (abs(event.pos[0] - self.click_origin[0]) + abs(event.pos[1] - self.click_origin[1])) > 12: self.click_time = None dx = event.pos[0] - self.dragging[0] dy = event.pos[1] - self.dragging[1] if event.buttons[0]: # left mouse button self.zoom(1.003 ** (dx+dy)) else: self.viewer.shiftoffset(-2*dx, -2*dy) self.updated_viewer() self.dragging = event.pos self.must_redraw = True else: self.notifymousepos(event.pos) def process_MouseButtonDown(self, event): self.dragging = self.click_origin = event.pos self.click_time = time.time() # pygame.event.set_grab(True) def process_MouseButtonUp(self, event): self.dragging = None pygame.event.set_grab(False) if self.click_time is not None and abs(time.time() - self.click_time) < 1: # click (no significant dragging) self.notifyclick(self.click_origin) self.click_time = None else: self.update_status_bar() self.click_time = None self.notifymousepos(event.pos) def process_KeyDown(self, event): mod = event.mod & self.key_mask method, args = self.key_cache.get((event.key, mod), (None, None)) if method is None and event.unicode: char = event.unicode.lower() mod = mod & ~ KMOD_SHIFT method, args = self.ascii_key_cache.get((char, mod), (None, None)) if method is not None: method(*args) def process_VideoResize(self, event): # short-circuit if there are more resize events pending if self.peek(VIDEORESIZE): return # XXX sometimes some jerk are trying to minimise our window, # discard such event (we see a height of 5 in this case). # XXX very specific MacOS/X workaround: after resizing the window # to a height of 1 and back, we get two bogus VideoResize events, # for height 16 and 32. # XXX summary: let's ignore all resize events with a height <= 32 if event.size[1] <= 32: return self.resize(event.size) self.must_redraw = True def process_Quit(self, event): self.quit() def process_UserEvent(self, event): # new layout request if hasattr(event, 'layout'): if event.layout is None: self.setstatusbar('cannot follow this link') else: self.setlayout(event.layout) elif hasattr(event, 'say'): self.setstatusbar(event.say) def quit(self): raise StopIteration def redraw_now(self): self.viewer.render() if self.statusbarinfo: self.drawstatusbar() else: self.status_bar_height = 0 pygame.display.flip() self.must_redraw = False def run1(self): self.dragging = self.click_origin = self.click_time = None try: while True: if self.must_redraw and not EventQueue: self.redraw_now() if not EventQueue: wait_for_events() self.process_event(EventQueue.pop(0)) except StopIteration: pass def run(self): self.run1() # cannot safely close and re-open the display, depending on # Pygame version and platform. pygame.display.set_mode((self.width,1)) def shortlabel(label): """Shorten a graph node label.""" return label and label.replace('\\l', '\n').splitlines()[0] def renderline(text, font, fgcolor, width, maxheight=sys.maxint, overflowcolor=None): """Render a single line of text into a list of images. Performs word wrapping. """ if overflowcolor is None: overflowcolor = fgcolor words = text.split(' ') lines = [] while words: line = words.pop(0) img = font.render(line or ' ', 1, fgcolor) while words: longerline = line + ' ' + words[0] longerimg = font.render(longerline, 1, fgcolor) w, h = longerimg.get_size() if w > width: break words.pop(0) line = longerline img = longerimg w, h = img.get_size() if h > maxheight: img = font.render('...', 1, overflowcolor) w, h = img.get_size() while lines and h > maxheight: maxheight += lines.pop().get_size()[1] lines.append(img) break maxheight -= h lines.append(img) return lines def rendertext(text, font, fgcolor, width, maxheight=sys.maxint, overflowcolor=None): """Render a multiline string into a list of images. Performs word wrapping for each line individually.""" lines = [] for line in text.splitlines(): l = renderline(line, font, fgcolor, width, maxheight, overflowcolor) lines.extend(l) maxheight -= totalheight(l) if maxheight <= 0: break return lines def totalheight(lines): """Calculate the total height of a list of images.""" totalh = 0 for img in lines: w, h = img.get_size() totalh += h return totalh
Python
#! /usr/bin/env python """ Command-line interface for a dot file viewer. dotviewer.py filename.dot dotviewer.py filename.plain dotviewer.py --server [interface:]port In the first form, show the graph contained in a .dot file. In the second form, the graph was already compiled to a .plain file. In the third form, listen for connexion on the given port and display the graphs sent by the remote side. On the remote site, set the GRAPHSERVER environment variable to HOST:PORT. """ import sys def main(args = sys.argv[1:]): import getopt options, args = getopt.getopt(args, 's:h', ['server=', 'help']) server_addr = None for option, value in options: if option in ('-h', '--help'): print >> sys.stderr, __doc__ sys.exit(2) if option in ('-s', '--server'): server_addr = value if not args and server_addr is None: print >> sys.stderr, __doc__ sys.exit(2) for filename in args: import graphclient graphclient.display_dot_file(filename) if server_addr is not None: import graphserver graphserver.listen_server(server_addr) if __name__ == '__main__': main()
Python
""" Graph file parsing. """ import os, sys, re import msgstruct re_nonword = re.compile(r'([^0-9a-zA-Z_.]+)') re_plain = re.compile(r'graph [-0-9.]+ [-0-9.]+ [-0-9.]+$', re.MULTILINE) re_digraph = re.compile(r'\b(graph|digraph)\b', re.IGNORECASE) def guess_type(content): # try to see whether it is a directed graph or not, # or already a .plain file # XXX not a perfect heursitic if re_plain.match(content): return 'plain' # already a .plain file # look for the word 'graph' or 'digraph' followed by a '{'. bracepos = None lastfound = '' for match in re_digraph.finditer(content): position = match.start() if bracepos is None: bracepos = content.find('{', position) if bracepos < 0: break elif position > bracepos: break lastfound = match.group() if lastfound.lower() == 'digraph': return 'dot' if lastfound.lower() == 'graph': return 'neato' print >> sys.stderr, "Warning: could not guess file type, using 'dot'" return 'unknown' def dot2plain(content, contenttype, use_codespeak=False): if contenttype == 'plain': # already a .plain file return content if not use_codespeak: if contenttype != 'neato': cmdline = 'dot -Tplain' else: cmdline = 'neato -Tplain' #print >> sys.stderr, '* running:', cmdline child_in, child_out = os.popen2(cmdline, 'r') try: import thread except ImportError: bkgndwrite(child_in, content) else: thread.start_new_thread(bkgndwrite, (child_in, content)) plaincontent = child_out.read() child_out.close() if not plaincontent: # 'dot' is likely not installed raise PlainParseError("no result from running 'dot'") else: import urllib request = urllib.urlencode({'dot': content}) url = 'http://codespeak.net/pypy/convertdot.cgi' print >> sys.stderr, '* posting:', url g = urllib.urlopen(url, data=request) result = [] while True: data = g.read(16384) if not data: break result.append(data) g.close() plaincontent = ''.join(result) # very simple-minded way to give a somewhat better error message if plaincontent.startswith('<body'): raise Exception("the dot on codespeak has very likely crashed") return plaincontent def bkgndwrite(f, data): f.write(data) f.close() class PlainParseError(Exception): pass def splitline(line, re_word = re.compile(r'[^\s"]\S*|["]["]|["].*?[^\\]["]')): result = [] for word in re_word.findall(line): if word.startswith('"'): word = eval(word) result.append(word) return result def parse_plain(graph_id, plaincontent, links={}, fixedfont=False): lines = plaincontent.splitlines(True) for i in range(len(lines)-2, -1, -1): if lines[i].endswith('\\\n'): # line ending in '\' lines[i] = lines[i][:-2] + lines[i+1] del lines[i+1] header = splitline(lines.pop(0)) if header[0] != 'graph': raise PlainParseError("should start with 'graph'") yield (msgstruct.CMSG_START_GRAPH, graph_id) + tuple(header[1:]) texts = [] for line in lines: line = splitline(line) if line[0] == 'node': if len(line) != 11: raise PlainParseError("bad 'node'") yield (msgstruct.CMSG_ADD_NODE,) + tuple(line[1:]) texts.append(line[6]) if line[0] == 'edge': yield (msgstruct.CMSG_ADD_EDGE,) + tuple(line[1:]) i = 4 + 2 * int(line[3]) if len(line) > i + 2: texts.append(line[i]) if line[0] == 'stop': break if links: # only include the links that really appear in the graph seen = {} for text in texts: for word in re_nonword.split(text): if word and word in links and word not in seen: t = links[word] if isinstance(t, tuple): statusbartext, color = t else: statusbartext = t color = None if color is not None: yield (msgstruct.CMSG_ADD_LINK, word, statusbartext, color[0], color[1], color[2]) else: yield (msgstruct.CMSG_ADD_LINK, word, statusbartext) seen[word] = True if fixedfont: yield (msgstruct.CMSG_FIXED_FONT,) yield (msgstruct.CMSG_STOP_GRAPH,) def parse_dot(graph_id, content, links={}, fixedfont=False): contenttype = guess_type(content) try: plaincontent = dot2plain(content, contenttype, use_codespeak=False) return list(parse_plain(graph_id, plaincontent, links, fixedfont)) except PlainParseError: # failed, retry via codespeak plaincontent = dot2plain(content, contenttype, use_codespeak=True) return list(parse_plain(graph_id, plaincontent, links, fixedfont))
Python
class GraphPage(object): """Base class for the client-side content of one of the 'pages' (one graph) sent over to and displayed by the external process. """ save_tmp_file = None def __init__(self, *args): self.args = args def content(self): """Compute the content of the page. This doesn't modify the page in place; it returns a new GraphPage. """ if hasattr(self, 'source'): return self else: new = self.__class__() new.source = '' # '''dot source''' new.links = {} # {'word': 'statusbar text'} new.compute(*self.args) # defined in subclasses return new def followlink(self, word): raise KeyError def display(self): "Display a graph page." import graphclient, msgstruct try: graphclient.display_page(self, save_tmp_file=self.save_tmp_file) except msgstruct.RemoteError, e: import sys print >> sys.stderr, "Exception in the graph viewer:", str(e) def display_background(self): "Display a graph page in a background thread." try: import thread thread.start_new_thread(self.display, ()) except ImportError: self.display() class DotFileGraphPage(GraphPage): def compute(self, dotfile): f = open(dotfile, 'r') self.source = f.read() f.close()
Python
import sys, os def get_terminal_width(): try: import termios,fcntl,struct call = fcntl.ioctl(0,termios.TIOCGWINSZ,"\000"*8) height,width = struct.unpack( "hhhh", call ) [:2] terminal_width = width except (SystemExit, KeyboardInterrupt), e: raise except: # FALLBACK terminal_width = int(os.environ.get('COLUMNS', 80))-1 return terminal_width terminal_width = get_terminal_width() def ansi_print(text, esc, file=None, newline=True, flush=False): if file is None: file = sys.stderr text = text.rstrip() if esc and sys.platform != "win32" and file.isatty(): if not isinstance(esc, tuple): esc = (esc,) text = (''.join(['\x1b[%sm' % cod for cod in esc]) + text + '\x1b[0m') # ANSI color code "reset" if newline: text += '\n' file.write(text) if flush: file.flush()
Python
import py import errno class Error(EnvironmentError): __module__ = 'py.error' def __repr__(self): return "%s.%s %r: %s " %(self.__class__.__module__, self.__class__.__name__, self.__class__.__doc__, " ".join(map(str, self.args)), #repr(self.args) ) def __str__(self): return "[%s]: %s" %(self.__class__.__doc__, " ".join(map(str, self.args)), ) _winerrnomap = { 2: errno.ENOENT, 3: errno.ENOENT, 17: errno.EEXIST, 22: errno.ENOTDIR, 267: errno.ENOTDIR, 5: errno.EACCES, # anything better? } # note: 'py.std' may not be imported yet at all, because # the 'error' module in this file is imported very early. # This is dependent on dict order. ModuleType = type(py) class py_error(ModuleType): """ py.error lazily provides higher level Exception classes for each possible POSIX errno (as defined per the 'errno' module. All such Exceptions derive from py.error.Error, which itself is a subclass of EnvironmentError. """ Error = Error def _getwinerrnoclass(cls, eno): return cls._geterrnoclass(_winerrnomap[eno]) _getwinerrnoclass = classmethod(_getwinerrnoclass) def _geterrnoclass(eno, _errno2class = {}): try: return _errno2class[eno] except KeyError: clsname = py.std.errno.errorcode.get(eno, "UnknownErrno%d" %(eno,)) cls = type(Error)(clsname, (Error,), {'__module__':'py.error', '__doc__': py.std.os.strerror(eno)}) _errno2class[eno] = cls return cls _geterrnoclass = staticmethod(_geterrnoclass) def __getattr__(self, name): eno = getattr(py.std.errno, name) cls = self._geterrnoclass(eno) setattr(self, name, cls) return cls def getdict(self, done=[]): try: return done[0] except IndexError: for name in py.std.errno.errorcode.values(): hasattr(self, name) # force attribute to be loaded, ignore errors dictdescr = ModuleType.__dict__['__dict__'] done.append(dictdescr.__get__(self)) return done[0] __dict__ = property(getdict) del getdict error = py_error('py.error', py_error.__doc__)
Python
""" A utility to build a Python extension module from C, wrapping distutils. """ import py # XXX we should distutils in a subprocess, because it messes up the # environment and who knows what else. Currently we just save # and restore os.environ. def make_module_from_c(cfile): import os, sys, imp from distutils.core import setup from distutils.extension import Extension debug = 0 #try: # from distutils.log import set_threshold # set_threshold(10000) #except ImportError: # print "ERROR IMPORTING" # pass dirpath = cfile.dirpath() modname = cfile.purebasename # find the expected extension of the compiled C module for ext, mode, filetype in imp.get_suffixes(): if filetype == imp.C_EXTENSION: break else: raise ImportError, "cannot find the file name suffix of C ext modules" lib = dirpath.join(modname+ext) # XXX argl! we need better "build"-locations alltogether! if lib.check(): try: lib.remove() except EnvironmentError: pass # XXX we just use the existing version, bah if not lib.check(): c = py.io.StdCaptureFD() try: try: saved_environ = os.environ.items() try: lastdir = dirpath.chdir() try: setup( name = "pylibmodules", ext_modules=[ Extension(modname, [str(cfile)]) ], script_name = 'setup.py', script_args = ['-q', 'build_ext', '--inplace'] #script_args = ['build_ext', '--inplace'] ) finally: lastdir.chdir() finally: for key, value in saved_environ: if os.environ.get(key) != value: os.environ[key] = value finally: foutput, foutput = c.done() except KeyboardInterrupt: raise except SystemExit, e: raise RuntimeError("cannot compile %s: %s\n%s" % (cfile, e, foutput.read())) # XXX do we need to do some check on fout/ferr? # XXX not a nice way to import a module if debug: print "inserting path to sys.path", dirpath sys.path.insert(0, str(dirpath)) if debug: print "import %(modname)s as testmodule" % locals() exec py.code.compile("import %(modname)s as testmodule" % locals()) try: sys.path.remove(str(dirpath)) except ValueError: pass return testmodule
Python
import py import sys, os, re from distutils import sysconfig from distutils import core winextensions = 1 if sys.platform == 'win32': try: import _winreg, win32gui, win32con except ImportError: winextensions = 0 class Params: """ a crazy hack to convince distutils to please install all of our files inside the package. """ _sitepackages = py.path.local(sysconfig.get_python_lib()) def __init__(self, pkgmod): name = pkgmod.__name__ self._pkgdir = py.path.local(pkgmod.__file__).dirpath() self._rootdir = self._pkgdir.dirpath() self._pkgtarget = self._sitepackages.join(name) self._datadict = {} self.packages = [] self.scripts = [] self.hacktree() self.data_files = self._datadict.items() self.data_files.sort() self.packages.sort() self.scripts.sort() def hacktree(self): for p in self._pkgdir.visit(None, lambda x: x.basename != '.svn'): if p.check(file=1): if p.ext in ('.pyc', '.pyo'): continue if p.dirpath().basename == 'bin': self.scripts.append(p.relto(self._rootdir)) self.adddatafile(p) elif p.ext == '.py': self.addpythonfile(p) else: self.adddatafile(p) #else: # if not p.listdir(): # self.adddatafile(p.ensure('dummy')) def adddatafile(self, p): if p.ext in ('.pyc', 'pyo'): return target = self._pkgtarget.join(p.dirpath().relto(self._pkgdir)) l = self._datadict.setdefault(str(target), []) l.append(p.relto(self._rootdir)) def addpythonfile(self, p): parts = p.parts() for above in p.parts(reverse=True)[1:]: if self._pkgdir.relto(above): dottedname = p.dirpath().relto(self._rootdir).replace(p.sep, '.') if dottedname not in self.packages: self.packages.append(dottedname) break if not above.join('__init__.py').check(): self.adddatafile(p) #print "warning, added data file", p break #if sys.platform != 'win32': # scripts.remove('py/bin/pytest.cmd') #else: # scripts.remove('py/bin/py.test') # ### helpers: def checknonsvndir(p): if p.basename != '.svn' and p.check(dir=1): return True def dump(params): print "packages" for x in params.packages: print "package ", x print print "scripts" for x in params.scripts: print "script ", x print print "data files" for x in params.data_files: print "data file ", x print def addbindir2path(): if sys.platform != 'win32' or not winextensions: return # Add py/bin to PATH environment variable bindir = os.path.join(sysconfig.get_python_lib(), "py", "bin", "win32") reg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) key = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment" path = get_registry_value(reg, key, "Path") path += ";" + bindir print "Setting PATH to:", path set_registry_value(reg, key, "Path", path) #print "Current PATH is:", get_registry_value(reg, key, "Path") # Propagate changes throughout the system win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, "Environment", win32con.SMTO_ABORTIFHUNG, 5000) # Propagate changes to current command prompt os.system("set PATH=%s" % path) def get_registry_value(reg, key, value_name): k = _winreg.OpenKey(reg, key) value = _winreg.QueryValueEx(k, value_name)[0] _winreg.CloseKey(k) return value def set_registry_value(reg, key, value_name, value): k = _winreg.OpenKey(reg, key, 0, _winreg.KEY_WRITE) value_type = _winreg.REG_SZ # if we handle the Path value, then set its type to REG_EXPAND_SZ # so that things like %SystemRoot% get automatically expanded by the # command prompt if value_name == "Path": value_type = _winreg.REG_EXPAND_SZ _winreg.SetValueEx(k, value_name, 0, value_type, value) _winreg.CloseKey(k) ### end helpers def setup(pkg, **kw): """ invoke distutils on a given package. """ if 'install' in sys.argv[1:]: print "precompiling greenlet module" try: x = py.magic.greenlet() except (RuntimeError, ImportError): print "could not precompile greenlet module, skipping" params = Params(pkg) #dump(params) source = getattr(pkg, '__package__', pkg) namelist = list(core.setup_keywords) namelist.extend(['packages', 'scripts', 'data_files']) for name in namelist: for ns in (source, params): if hasattr(ns, name): kw[name] = getattr(ns, name) break #script_args = sys.argv[1:] #if 'install' in script_args: # script_args = ['--quiet'] + script_args # #print "installing", py #py.std.pprint.pprint(kw) core.setup(**kw) if 'install' in sys.argv[1:]: addbindir2path() x = params._rootdir.join('build') if x.check(): print "removing", x x.remove()
Python
import py _time_desc = { 1 : 'second', 60 : 'minute', 3600 : 'hour', 86400 : 'day', 2628000 : 'month', 31536000 : 'year', } def worded_diff_time(ctime): difftime = py.std.time.time() - ctime keys = _time_desc.keys() keys.sort() for i, key in py.builtin.enumerate(keys): if key >=difftime: break l = [] keylist = keys[:i] keylist.reverse() for key in keylist[:1]: div = int(difftime / key) if div==0: break difftime -= div * key plural = div > 1 and 's' or '' l.append('%d %s%s' %(div, _time_desc[key], plural)) return ", ".join(l) + " ago " _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def worded_time(ctime): tm = py.std.time.gmtime(ctime) return "%s %d, %d" % (_months[tm.tm_mon-1], tm.tm_mday, tm.tm_year)
Python
import sys class Std(object): """ makes all standard python modules available as a lazily computed attribute. """ def __init__(self): self.__dict__ = sys.modules def __getattr__(self, name): try: m = __import__(name) except ImportError: raise AttributeError("py.std: could not import %s" % name) return m std = Std()
Python
""" """ import py import sys log = py.log.get("dynpkg", info=py.log.STDOUT, debug=py.log.STDOUT, command=None) # py.log.STDOUT) from distutils import util class DistPython: def __init__(self, location=None, python=None): if python is None: python = py.std.sys.executable self.python = python if location is None: location = py.path.local() self.location = location self.plat_specifier = '.%s-%s' % (util.get_platform(), sys.version[0:3]) def clean(self): out = self._exec("clean -a") #print out def build(self): out = self._exec("build") #print out def _exec(self, cmd): python = self.python old = self.location.chdir() try: cmd = "%(python)s setup.py %(cmd)s" % locals() log.command(cmd) out = py.process.cmdexec(cmd) finally: old.chdir() return out def get_package_path(self, pkgname): pkg = self._get_package_path(pkgname) if pkg is None: #self.clean() self.build() pkg = self._get_package_path(pkgname) assert pkg is not None return pkg def _get_package_path(self, pkgname): major, minor = py.std.sys.version_info[:2] #assert major >=2 and minor in (3,4,5) suffix = "%s.%s" %(major, minor) location = self.location for base in [location.join('build', 'lib'), location.join('build', 'lib'+ self.plat_specifier)]: if base.check(dir=1): for pkg in base.visit(lambda x: x.check(dir=1)): if pkg.basename == pkgname: # if pkg.dirpath().basename == 'lib'+ self.plat_specifier or \ pkg.dirpath().basename == 'lib': return pkg def setpkg(finalpkgname, distdir): assert distdir.check(dir=1) dist = DistPython(distdir) pkg = dist.get_package_path(finalpkgname) assert pkg.check(dir=1) sys.path.insert(0, str(pkg.dirpath())) try: modname = pkg.purebasename if modname in sys.modules: log.debug("removing from sys.modules:", modname) del sys.modules[modname] sys.modules[modname] = mod = __import__(modname) finally: sys.path[0] # XXX log.info("module is at", mod.__file__) return mod
Python
import py import sys, os, traceback import re if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): def log(msg): print msg else: def log(msg): pass def convert_rest_html(source, source_path, stylesheet=None, encoding='latin1'): from py.__.rest import directive """ return html latin1-encoded document for the given input. source a ReST-string sourcepath where to look for includes (basically) stylesheet path (to be used if any) """ from docutils.core import publish_string directive.set_backend_and_register_directives("html") kwargs = { 'stylesheet' : stylesheet, 'stylesheet_path': None, 'traceback' : 1, 'embed_stylesheet': 0, 'output_encoding' : encoding, #'halt' : 0, # 'info', 'halt_level' : 2, } # docutils uses os.getcwd() :-( source_path = os.path.abspath(str(source_path)) prevdir = os.getcwd() try: os.chdir(os.path.dirname(source_path)) return publish_string(source, source_path, writer_name='html', settings_overrides=kwargs) finally: os.chdir(prevdir) def process(txtpath, encoding='latin1'): """ process a textfile """ log("processing %s" % txtpath) assert txtpath.check(ext='.txt') if isinstance(txtpath, py.path.svnwc): txtpath = txtpath.localpath htmlpath = txtpath.new(ext='.html') #svninfopath = txtpath.localpath.new(ext='.svninfo') style = txtpath.dirpath('style.css') if style.check(): stylesheet = style.basename else: stylesheet = None content = unicode(txtpath.read(), encoding) doc = convert_rest_html(content, txtpath, stylesheet=stylesheet, encoding=encoding) htmlpath.write(doc) #log("wrote %r" % htmlpath) #if txtpath.check(svnwc=1, versioned=1): # info = txtpath.info() # svninfopath.dump(info) rex1 = re.compile(ur'.*<body>(.*)</body>.*', re.MULTILINE | re.DOTALL) rex2 = re.compile(ur'.*<div class="document">(.*)</div>.*', re.MULTILINE | re.DOTALL) def strip_html_header(string, encoding='utf8'): """ return the content of the body-tag """ uni = unicode(string, encoding) for rex in rex1,rex2: match = rex.search(uni) if not match: break uni = match.group(1) return uni
Python
#!/usr/bin/env python import py import inspect import types def report_strange_docstring(name, obj): if obj.__doc__ is None: print "%s misses a docstring" % (name, ) elif obj.__doc__ == "": print "%s has an empty" % (name, ) elif "XXX" in obj.__doc__: print "%s has an 'XXX' in its docstring" % (name, ) def find_code(method): return getattr(getattr(method, "im_func", None), "func_code", None) def report_different_parameter_names(name, cls): bases = cls.__mro__ for base in bases: for attr in dir(base): meth1 = getattr(base, attr) code1 = find_code(meth1) if code1 is None: continue if not callable(meth1): continue if not hasattr(cls, attr): continue meth2 = getattr(cls, attr) code2 = find_code(meth2) if not callable(meth2): continue if code2 is None: continue args1 = inspect.getargs(code1)[0] args2 = inspect.getargs(code2)[0] for a1, a2 in zip(args1, args2): if a1 != a2: print "%s.%s have different argument names %s, %s than the version in %s" % (name, attr, a1, a2, base) def find_all_exported(): stack = [(name, getattr(py, name)) for name in dir(py)[::-1] if not name.startswith("_") and name != "compat"] seen = {} exported = [] while stack: name, obj = stack.pop() if id(obj) in seen: continue else: seen[id(obj)] = True exported.append((name, obj)) if isinstance(obj, type) or isinstance(obj, type(py)): stack.extend([("%s.%s" % (name, s), getattr(obj, s)) for s in dir(obj) if len(s) <= 1 or not (s[0] == '_' and s[1] != '_')]) return exported if __name__ == '__main__': all_exported = find_all_exported() print "strange docstrings" print "==================" print for name, obj in all_exported: if callable(obj): report_strange_docstring(name, obj) print "\n\ndifferent parameters" print "====================" print for name, obj in all_exported: if isinstance(obj, type): report_different_parameter_names(name, obj)
Python
#!/usr/bin/env python # hands on script to compute the non-empty Lines of Code # for tests and non-test code import py curdir = py.path.local() def nodot(p): return p.check(dotfile=0) class FileCounter(object): def __init__(self): self.file2numlines = {} self.numlines = 0 self.numfiles = 0 def addrecursive(self, directory, fil="*.py", rec=nodot): for x in directory.visit(fil, rec): self.addfile(x) def addfile(self, fn, emptylines=False): if emptylines: s = len(p.readlines()) else: s = 0 for i in fn.readlines(): if i.strip(): s += 1 self.file2numlines[fn] = s self.numfiles += 1 self.numlines += s def getnumlines(self, fil): numlines = 0 for path, value in self.file2numlines.items(): if fil(path): numlines += value return numlines def getnumfiles(self, fil): numfiles = 0 for path in self.file2numlines: if fil(path): numfiles += 1 return numfiles def get_loccount(locations=None): if locations is None: localtions = [py.path.local()] counter = FileCounter() for loc in locations: counter.addrecursive(loc, '*.py', rec=nodot) def istestfile(p): return p.check(fnmatch='test_*.py') isnottestfile = lambda x: not istestfile(x) numfiles = counter.getnumfiles(isnottestfile) numlines = counter.getnumlines(isnottestfile) numtestfiles = counter.getnumfiles(istestfile) numtestlines = counter.getnumlines(istestfile) return counter, numfiles, numlines, numtestfiles, numtestlines def countloc(paths=None): if not paths: paths = ['.'] locations = [py.path.local(x) for x in paths] (counter, numfiles, numlines, numtestfiles, numtestlines) = get_loccount(locations) items = counter.file2numlines.items() items.sort(lambda x,y: cmp(x[1], y[1])) for x, y in items: print "%3d %30s" % (y,x) print "%30s %3d" %("number of testfiles", numtestfiles) print "%30s %3d" %("number of non-empty testlines", numtestlines) print "%30s %3d" %("number of files", numfiles) print "%30s %3d" %("number of non-empty lines", numlines)
Python
#
Python
#!/usr/bin/env python # hands on script to compute the non-empty Lines of Code # for tests and non-test code import py curdir = py.path.local() def nodot(p): return p.check(dotfile=0) class FileCounter(object): def __init__(self): self.file2numlines = {} self.numlines = 0 self.numfiles = 0 def addrecursive(self, directory, fil="*.py", rec=nodot): for x in directory.visit(fil, rec): self.addfile(x) def addfile(self, fn, emptylines=False): if emptylines: s = len(p.readlines()) else: s = 0 for i in fn.readlines(): if i.strip(): s += 1 self.file2numlines[fn] = s self.numfiles += 1 self.numlines += s def getnumlines(self, fil): numlines = 0 for path, value in self.file2numlines.items(): if fil(path): numlines += value return numlines def getnumfiles(self, fil): numfiles = 0 for path in self.file2numlines: if fil(path): numfiles += 1 return numfiles def get_loccount(locations=None): if locations is None: localtions = [py.path.local()] counter = FileCounter() for loc in locations: counter.addrecursive(loc, '*.py', rec=nodot) def istestfile(p): return p.check(fnmatch='test_*.py') isnottestfile = lambda x: not istestfile(x) numfiles = counter.getnumfiles(isnottestfile) numlines = counter.getnumlines(isnottestfile) numtestfiles = counter.getnumfiles(istestfile) numtestlines = counter.getnumlines(istestfile) return counter, numfiles, numlines, numtestfiles, numtestlines def countloc(paths=None): if not paths: paths = ['.'] locations = [py.path.local(x) for x in paths] (counter, numfiles, numlines, numtestfiles, numtestlines) = get_loccount(locations) items = counter.file2numlines.items() items.sort(lambda x,y: cmp(x[1], y[1])) for x, y in items: print "%3d %30s" % (y,x) print "%30s %3d" %("number of testfiles", numtestfiles) print "%30s %3d" %("number of non-empty testlines", numtestlines) print "%30s %3d" %("number of files", numfiles) print "%30s %3d" %("number of non-empty lines", numlines)
Python
import py class ChangeItem: def __init__(self, repo, revision, line): self.repo = py.path.local(repo) self.revision = int(revision) self.action = action = line[:4] self.path = line[4:].strip() self.added = action[0] == "A" self.modified = action[0] == "M" self.propchanged = action[1] == "U" self.deleted = action[0] == "D" def svnurl(self): return py.path.svnurl("file://%s/%s" %(self.repo, self.path), self.revision) def __repr__(self): return "<ChangeItem %r>" %(self.action + self.path) def changed(repo, revision): out = py.process.cmdexec("svnlook changed -r %s %s" %(revision, repo)) l = [] for line in out.strip().split('\n'): l.append(ChangeItem(repo, revision, line)) return l def author(repo, revision): out = py.process.cmdexec("svnlook author -r %s %s" %(revision, repo)) return out.strip() def youngest(repo): out = py.process.cmdexec("svnlook youngest %s" %(repo,)) return int(out)
Python
""" Put this file as 'conftest.py' somewhere upwards from py-trunk, modify the "socketserveradr" below to point to a windows/linux host running "py/execnet/script/loop_socketserver.py" and invoke e.g. from linux: py.test --session=MySession some_path_to_what_you_want_to_test This should ad-hoc distribute the running of tests to the remote machine (including rsyncing your WC). """ import py from py.__.test.terminal.remote import RemoteTerminalSession import os class MyRSync(py.execnet.RSync): def filter(self, path): if path.endswith('.pyc') or path.endswith('~'): return False dir, base = os.path.split(path) # we may want to have revision info on the other side, # so let's not exclude .svn directories #if base == '.svn': # return False return True class MySession(RemoteTerminalSession): socketserveradr = ('10.9.2.62', 8888) socketserveradr = ('10.9.4.148', 8888) def _initslavegateway(self): print "MASTER: initializing remote socket gateway" gw = py.execnet.SocketGateway(*self.socketserveradr) pkgname = 'py' # xxx flexibilize channel = gw.remote_exec(""" import os topdir = os.path.join(os.environ['HOMEPATH'], 'pytestcache') pkgdir = os.path.join(topdir, %r) channel.send((topdir, pkgdir)) """ % (pkgname,)) remotetopdir, remotepkgdir = channel.receive() sendpath = py.path.local(py.__file__).dirpath() rsync = MyRSync(sendpath) rsync.add_target(gw, remotepkgdir, delete=True) rsync.send() channel = gw.remote_exec(""" import os, sys path = %r # os.path.abspath sys.path.insert(0, path) os.chdir(path) import py channel.send((path, py.__file__)) """ % remotetopdir) topdir, remotepypath = channel.receive() assert topdir == remotetopdir, (topdir, remotetopdir) assert remotepypath.startswith(topdir), (remotepypath, topdir) #print "remote side has rsynced pythonpath ready: %r" %(topdir,) return gw, topdir dist_hosts = ['localhost', 'cobra', 'cobra']
Python
#
Python
#!/usr/bin/env python import py import inspect import types def report_strange_docstring(name, obj): if obj.__doc__ is None: print "%s misses a docstring" % (name, ) elif obj.__doc__ == "": print "%s has an empty" % (name, ) elif "XXX" in obj.__doc__: print "%s has an 'XXX' in its docstring" % (name, ) def find_code(method): return getattr(getattr(method, "im_func", None), "func_code", None) def report_different_parameter_names(name, cls): bases = cls.__mro__ for base in bases: for attr in dir(base): meth1 = getattr(base, attr) code1 = find_code(meth1) if code1 is None: continue if not callable(meth1): continue if not hasattr(cls, attr): continue meth2 = getattr(cls, attr) code2 = find_code(meth2) if not callable(meth2): continue if code2 is None: continue args1 = inspect.getargs(code1)[0] args2 = inspect.getargs(code2)[0] for a1, a2 in zip(args1, args2): if a1 != a2: print "%s.%s have different argument names %s, %s than the version in %s" % (name, attr, a1, a2, base) def find_all_exported(): stack = [(name, getattr(py, name)) for name in dir(py)[::-1] if not name.startswith("_") and name != "compat"] seen = {} exported = [] while stack: name, obj = stack.pop() if id(obj) in seen: continue else: seen[id(obj)] = True exported.append((name, obj)) if isinstance(obj, type) or isinstance(obj, type(py)): stack.extend([("%s.%s" % (name, s), getattr(obj, s)) for s in dir(obj) if len(s) <= 1 or not (s[0] == '_' and s[1] != '_')]) return exported if __name__ == '__main__': all_exported = find_all_exported() print "strange docstrings" print "==================" print for name, obj in all_exported: if callable(obj): report_strange_docstring(name, obj) print "\n\ndifferent parameters" print "====================" print for name, obj in all_exported: if isinstance(obj, type): report_different_parameter_names(name, obj)
Python
#
Python
import py import os, sys def killproc(pid): if sys.platform == "win32": py.process.cmdexec("taskkill /F /PID %d" %(pid,)) else: os.kill(pid, 15)
Python
""" This module contains multithread-safe cache implementations. Caches mainly have a __getitem__ and getorbuild() method where the latter either just return a cached value or first builds the value. These are the current cache implementations: BuildcostAccessCache tracks building-time and accesses. Evicts by product of num-accesses * build-time. """ import py gettime = py.std.time.time class WeightedCountingEntry(object): def __init__(self, value, oneweight): self.num = 1 self._value = value self.oneweight = oneweight def weight(): def fget(self): return (self.num * self.oneweight, self.num) return property(fget, None, None, "cumulative weight") weight = weight() def value(): def fget(self): # you need to protect against mt-access at caller side! self.num += 1 return self._value return property(fget, None, None) value = value() def __repr__(self): return "<%s weight=%s>" % (self.__class__.__name__, self.weight) class BasicCache(object): def __init__(self, maxentries=128): self.maxentries = maxentries self.prunenum = int(maxentries - maxentries/8) self._lock = py.std.threading.RLock() self._dict = {} def getentry(self, key): lock = self._lock lock.acquire() try: return self._dict.get(key, None) finally: lock.release() def putentry(self, key, entry): self._lock.acquire() try: self._prunelowestweight() self._dict[key] = entry finally: self._lock.release() def delentry(self, key, raising=False): self._lock.acquire() try: try: del self._dict[key] except KeyError: if raising: raise finally: self._lock.release() def getorbuild(self, key, builder, *args, **kwargs): entry = self.getentry(key) if entry is None: entry = self.build(key, builder, *args, **kwargs) return entry.value def _prunelowestweight(self): """ prune out entries with lowest weight. """ # note: must be called with acquired self._lock! numentries = len(self._dict) if numentries >= self.maxentries: # evict according to entry's weight items = [(entry.weight, key) for key, entry in self._dict.iteritems()] items.sort() index = numentries - self.prunenum if index > 0: for weight, key in items[:index]: del self._dict[key] class BuildcostAccessCache(BasicCache): """ A BuildTime/Access-counting cache implementation. the weight of a value is computed as the product of num-accesses-of-a-value * time-to-build-the-value The values with the least such weights are evicted if the cache maxentries threshold is superceded. For implementation flexibility more than one object might be evicted at a time. """ # time function to use for measuring build-times _time = gettime def __init__(self, maxentries=64): super(BuildcostAccessCache, self).__init__(maxentries) def build(self, key, builder, *args, **kwargs): start = self._time() val = builder(*args, **kwargs) end = self._time() entry = WeightedCountingEntry(val, end-start) self.putentry(key, entry) return entry class AgingCache(BasicCache): """ This cache prunes out cache entries that are too old. """ def __init__(self, maxentries=128, maxseconds=10.0): super(AgingCache, self).__init__(maxentries) self.maxseconds = maxseconds def getentry(self, key): self._lock.acquire() try: try: entry = self._dict[key] except KeyError: entry = None else: if entry.isexpired(): del self._dict[key] entry = None return entry finally: self._lock.release() def build(self, key, builder, *args, **kwargs): ctime = gettime() val = builder(*args, **kwargs) entry = AgingEntry(val, ctime + self.maxseconds) self.putentry(key, entry) return entry class AgingEntry(object): def __init__(self, value, expirationtime): self.value = value self.weight = expirationtime def isexpired(self): t = py.std.time.time() return t >= self.weight
Python
import py, os, stat, md5 from Queue import Queue class RSync(object): """ This class allows to send a directory structure (recursively) to one or multiple remote filesystems. There is limited support for symlinks, which means that symlinks pointing to the sourcetree will be send "as is" while external symlinks will be just copied (regardless of existance of such a path on remote side). """ def __init__(self, sourcedir, callback=None, verbose=True): self._sourcedir = str(sourcedir) self._verbose = verbose assert callback is None or callable(callback) self._callback = callback self._channels = {} self._receivequeue = Queue() self._links = [] def filter(self, path): return True def _end_of_channel(self, channel): if channel in self._channels: # too early! we must have got an error channel.waitclose() # or else we raise one raise IOError('connection unexpectedly closed: %s ' % ( channel.gateway,)) def _process_link(self, channel): for link in self._links: channel.send(link) # completion marker, this host is done channel.send(42) def _done(self, channel): """ Call all callbacks """ finishedcallback = self._channels.pop(channel) if finishedcallback: finishedcallback() def _list_done(self, channel): # sum up all to send if self._callback: s = sum([self._paths[i] for i in self._to_send[channel]]) self._callback("list", s, channel) def _send_item(self, channel, data): """ Send one item """ modified_rel_path, checksum = data modifiedpath = os.path.join(self._sourcedir, *modified_rel_path) try: f = open(modifiedpath, 'rb') data = f.read() except IOError: data = None # provide info to progress callback function modified_rel_path = "/".join(modified_rel_path) if data is not None: self._paths[modified_rel_path] = len(data) else: self._paths[modified_rel_path] = 0 if channel not in self._to_send: self._to_send[channel] = [] self._to_send[channel].append(modified_rel_path) if data is not None: f.close() if checksum is not None and checksum == md5.md5(data).digest(): data = None # not really modified else: # ! there is a reason for the interning: # sharing multiple copies of the file's data data = intern(data) self._report_send_file(channel.gateway, modified_rel_path) channel.send(data) def _report_send_file(self, gateway, modified_rel_path): if self._verbose: print '%s <= %s' % (gateway.remoteaddress, modified_rel_path) def send(self, raises=True): """ Sends a sourcedir to all added targets. Flag indicates whether to raise an error or return in case of lack of targets """ if not self._channels: if raises: raise IOError("no targets available, maybe you " "are trying call send() twice?") return # normalize a trailing '/' away self._sourcedir = os.path.dirname(os.path.join(self._sourcedir, 'x')) # send directory structure and file timestamps/sizes self._send_directory_structure(self._sourcedir) # paths and to_send are only used for doing # progress-related callbacks self._paths = {} self._to_send = {} # send modified file to clients while self._channels: channel, req = self._receivequeue.get() if req is None: self._end_of_channel(channel) else: command, data = req if command == "links": self._process_link(channel) elif command == "done": self._done(channel) elif command == "ack": if self._callback: self._callback("ack", self._paths[data], channel) elif command == "list_done": self._list_done(channel) elif command == "send": self._send_item(channel, data) del data else: assert "Unknown command %s" % command def add_target(self, gateway, destdir, finishedcallback=None, **options): """ Adds a remote target specified via a 'gateway' and a remote destination directory. """ assert finishedcallback is None or callable(finishedcallback) for name in options: assert name in ('delete',) def itemcallback(req): self._receivequeue.put((channel, req)) channel = gateway.remote_exec(REMOTE_SOURCE) channel.setcallback(itemcallback, endmarker = None) channel.send((str(destdir), options)) self._channels[channel] = finishedcallback def _broadcast(self, msg): for channel in self._channels: channel.send(msg) def _send_link(self, basename, linkpoint): self._links.append(("link", basename, linkpoint)) def _send_directory(self, path): # dir: send a list of entries names = [] subpaths = [] for name in os.listdir(path): p = os.path.join(path, name) if self.filter(p): names.append(name) subpaths.append(p) self._broadcast(names) for p in subpaths: self._send_directory_structure(p) def _send_link_structure(self, path): linkpoint = os.readlink(path) basename = path[len(self._sourcedir) + 1:] if not linkpoint.startswith(os.sep): # relative link, just send it # XXX: do sth with ../ links self._send_link(basename, linkpoint) elif linkpoint.startswith(self._sourcedir): self._send_link(basename, linkpoint[len(self._sourcedir) + 1:]) else: self._send_link(basename, linkpoint) self._broadcast(None) def _send_directory_structure(self, path): try: st = os.lstat(path) except OSError: self._broadcast((0, 0)) return if stat.S_ISREG(st.st_mode): # regular file: send a timestamp/size pair self._broadcast((st.st_mtime, st.st_size)) elif stat.S_ISDIR(st.st_mode): self._send_directory(path) elif stat.S_ISLNK(st.st_mode): self._send_link_structure(path) else: raise ValueError, "cannot sync %r" % (path,) REMOTE_SOURCE = py.path.local(__file__).dirpath().\ join('rsync_remote.py').open().read() + "\nf()"
Python
import struct #import marshal # ___________________________________________________________________________ # # Messages # ___________________________________________________________________________ # the header format HDR_FORMAT = "!hhii" HDR_SIZE = struct.calcsize(HDR_FORMAT) class Message: """ encapsulates Messages and their wire protocol. """ _types = {} def __init__(self, channelid=0, data=''): self.channelid = channelid self.data = data def writeto(self, io): # XXX marshal.dumps doesn't work for exchanging data across Python # version :-((( There is no sane solution, short of a custom # pure Python marshaller data = self.data if isinstance(data, str): dataformat = 1 else: data = repr(self.data) # argh dataformat = 2 header = struct.pack(HDR_FORMAT, self.msgtype, dataformat, self.channelid, len(data)) io.write(header + data) def readfrom(cls, io): header = io.read(HDR_SIZE) (msgtype, dataformat, senderid, stringlen) = struct.unpack(HDR_FORMAT, header) data = io.read(stringlen) if dataformat == 1: pass elif dataformat == 2: data = eval(data, {}) # reversed argh else: raise ValueError("bad data format") msg = cls._types[msgtype](senderid, data) return msg readfrom = classmethod(readfrom) def post_sent(self, gateway, excinfo=None): pass def __repr__(self): r = repr(self.data) if len(r) > 50: return "<Message.%s channelid=%d len=%d>" %(self.__class__.__name__, self.channelid, len(r)) else: return "<Message.%s channelid=%d %r>" %(self.__class__.__name__, self.channelid, self.data) def _setupmessages(): class CHANNEL_OPEN(Message): def received(self, gateway): channel = gateway._channelfactory.new(self.channelid) gateway._local_schedulexec(channel=channel, sourcetask=self.data) class CHANNEL_NEW(Message): def received(self, gateway): """ receive a remotely created new (sub)channel. """ newid = self.data newchannel = gateway._channelfactory.new(newid) gateway._channelfactory._local_receive(self.channelid, newchannel) class CHANNEL_DATA(Message): def received(self, gateway): gateway._channelfactory._local_receive(self.channelid, self.data) class CHANNEL_CLOSE(Message): def received(self, gateway): gateway._channelfactory._local_close(self.channelid) class CHANNEL_CLOSE_ERROR(Message): def received(self, gateway): remote_error = gateway._channelfactory.RemoteError(self.data) gateway._channelfactory._local_close(self.channelid, remote_error) class CHANNEL_LAST_MESSAGE(Message): def received(self, gateway): gateway._channelfactory._local_last_message(self.channelid) classes = [x for x in locals().values() if hasattr(x, '__bases__')] classes.sort(lambda x,y : cmp(x.__name__, y.__name__)) i = 0 for cls in classes: Message._types[i] = cls cls.msgtype = i setattr(Message, cls.__name__, cls) i+=1 _setupmessages()
Python
import threading, weakref, sys import Queue if 'Message' not in globals(): from py.__.execnet.message import Message class RemoteError(EOFError): """ Contains an Exceptions from the other side. """ def __init__(self, formatted): self.formatted = formatted EOFError.__init__(self) def __str__(self): return self.formatted def __repr__(self): return "%s: %s" %(self.__class__.__name__, self.formatted) def warn(self): # XXX do this better print >> sys.stderr, "Warning: unhandled %r" % (self,) NO_ENDMARKER_WANTED = object() class Channel(object): """Communication channel between two possibly remote threads of code. """ RemoteError = RemoteError def __init__(self, gateway, id): assert isinstance(id, int) self.gateway = gateway self.id = id self._items = Queue.Queue() self._closed = False self._receiveclosed = threading.Event() self._remoteerrors = [] def setcallback(self, callback, endmarker=NO_ENDMARKER_WANTED): queue = self._items lock = self.gateway._channelfactory._receivelock lock.acquire() try: _callbacks = self.gateway._channelfactory._callbacks dictvalue = (callback, endmarker) if _callbacks.setdefault(self.id, dictvalue) != dictvalue: raise IOError("%r has callback already registered" %(self,)) self._items = None while 1: try: olditem = queue.get(block=False) except Queue.Empty: break else: if olditem is ENDMARKER: queue.put(olditem) break else: callback(olditem) if self._closed or self._receiveclosed.isSet(): # no need to keep a callback self.gateway._channelfactory._close_callback(self.id) finally: lock.release() def __repr__(self): flag = self.isclosed() and "closed" or "open" return "<Channel id=%d %s>" % (self.id, flag) def __del__(self): if self.gateway is None: # can be None in tests return self.gateway._trace("Channel(%d).__del__" % self.id) # no multithreading issues here, because we have the last ref to 'self' if self._closed: # state transition "closed" --> "deleted" for error in self._remoteerrors: error.warn() elif self._receiveclosed.isSet(): # state transition "sendonly" --> "deleted" # the remote channel is already in "deleted" state, nothing to do pass else: # state transition "opened" --> "deleted" if self._items is None: # has_callback Msg = Message.CHANNEL_LAST_MESSAGE else: Msg = Message.CHANNEL_CLOSE self.gateway._send(Msg(self.id)) def _getremoteerror(self): try: return self._remoteerrors.pop(0) except IndexError: return None # # public API for channel objects # def isclosed(self): """ return True if the channel is closed. A closed channel may still hold items. """ return self._closed def makefile(self, mode='w', proxyclose=False): """ return a file-like object. Only supported mode right now is 'w' for binary writes. If you want to have a subsequent file.close() mean to close the channel as well, then pass proxyclose=True. """ assert mode == 'w', "mode %r not availabe" %(mode,) return ChannelFile(channel=self, proxyclose=proxyclose) def close(self, error=None): """ close down this channel on both sides. """ if not self._closed: # state transition "opened/sendonly" --> "closed" # threads warning: the channel might be closed under our feet, # but it's never damaging to send too many CHANNEL_CLOSE messages put = self.gateway._send if error is not None: put(Message.CHANNEL_CLOSE_ERROR(self.id, str(error))) else: put(Message.CHANNEL_CLOSE(self.id)) if isinstance(error, RemoteError): self._remoteerrors.append(error) self._closed = True # --> "closed" self._receiveclosed.set() queue = self._items if queue is not None: queue.put(ENDMARKER) self.gateway._channelfactory._no_longer_opened(self.id) def waitclose(self, timeout=None): """ wait until this channel is closed (or the remote side otherwise signalled that no more data was being sent). The channel may still hold receiveable items, but not receive more. waitclose() reraises exceptions from executing code on the other side as channel.RemoteErrors containing a a textual representation of the remote traceback. """ self._receiveclosed.wait(timeout=timeout) # wait for non-"opened" state if not self._receiveclosed.isSet(): raise IOError, "Timeout" error = self._getremoteerror() if error: raise error def send(self, item): """sends the given item to the other side of the channel, possibly blocking if the sender queue is full. Note that an item needs to be marshallable. """ if self.isclosed(): raise IOError, "cannot send to %r" %(self,) if isinstance(item, Channel): data = Message.CHANNEL_NEW(self.id, item.id) else: data = Message.CHANNEL_DATA(self.id, item) self.gateway._send(data) def receive(self): """receives an item that was sent from the other side, possibly blocking if there is none. Note that exceptions from the other side will be reraised as channel.RemoteError exceptions containing a textual representation of the remote traceback. """ queue = self._items if queue is None: raise IOError("calling receive() on channel with receiver callback") x = queue.get() if x is ENDMARKER: queue.put(x) # for other receivers raise self._getremoteerror() or EOFError() else: return x def __iter__(self): return self def next(self): try: return self.receive() except EOFError: raise StopIteration # # helpers # ENDMARKER = object() class ChannelFactory(object): RemoteError = RemoteError def __init__(self, gateway, startcount=1): self._channels = weakref.WeakValueDictionary() self._callbacks = {} self._writelock = threading.Lock() self._receivelock = threading.RLock() self.gateway = gateway self.count = startcount self.finished = False def new(self, id=None): """ create a new Channel with 'id' (or create new id if None). """ self._writelock.acquire() try: if self.finished: raise IOError("connexion already closed: %s" % (self.gateway,)) if id is None: id = self.count self.count += 2 channel = Channel(self.gateway, id) self._channels[id] = channel return channel finally: self._writelock.release() def channels(self): return self._channels.values() # # internal methods, called from the receiver thread # def _no_longer_opened(self, id): try: del self._channels[id] except KeyError: pass self._close_callback(id) def _close_callback(self, id): try: callback, endmarker = self._callbacks.pop(id) except KeyError: pass else: if endmarker is not NO_ENDMARKER_WANTED: callback(endmarker) def _local_close(self, id, remoteerror=None): channel = self._channels.get(id) if channel is None: # channel already in "deleted" state if remoteerror: remoteerror.warn() else: # state transition to "closed" state if remoteerror: channel._remoteerrors.append(remoteerror) channel._closed = True # --> "closed" channel._receiveclosed.set() queue = channel._items if queue is not None: queue.put(ENDMARKER) self._no_longer_opened(id) def _local_last_message(self, id): channel = self._channels.get(id) if channel is None: # channel already in "deleted" state pass else: # state transition: if "opened", change to "sendonly" channel._receiveclosed.set() queue = channel._items if queue is not None: queue.put(ENDMARKER) self._no_longer_opened(id) def _local_receive(self, id, data): # executes in receiver thread self._receivelock.acquire() try: try: callback, endmarker = self._callbacks[id] except KeyError: channel = self._channels.get(id) queue = channel and channel._items if queue is None: pass # drop data else: queue.put(data) else: callback(data) # even if channel may be already closed finally: self._receivelock.release() def _finished_receiving(self): self._writelock.acquire() try: self.finished = True finally: self._writelock.release() for id in self._channels.keys(): self._local_last_message(id) for id in self._callbacks.keys(): self._close_callback(id) class ChannelFile: def __init__(self, channel, proxyclose=True): self.channel = channel self._proxyclose = proxyclose def write(self, out): self.channel.send(out) def flush(self): pass def close(self): if self._proxyclose: self.channel.close() def __repr__(self): state = self.channel.isclosed() and 'closed' or 'open' return '<ChannelFile %d %s>' %(self.channel.id, state)
Python
#! /usr/bin/env python """ a remote python shell for injection into startserver.py """ import sys, os, socket, select try: clientsock except NameError: print "client side starting" import sys host, port = sys.argv[1].split(':') port = int(port) myself = open(os.path.abspath(sys.argv[0]), 'rU').read() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(repr(myself)+'\n') print "send boot string" inputlist = [ sock, sys.stdin ] try: while 1: r,w,e = select.select(inputlist, [], []) if sys.stdin in r: line = raw_input() sock.sendall(line + '\n') if sock in r: line = sock.recv(4096) sys.stdout.write(line) sys.stdout.flush() except: import traceback print traceback.print_exc() sys.exit(1) print "server side starting" # server side # from traceback import print_exc from threading import Thread class promptagent(Thread): def __init__(self, clientsock): Thread.__init__(self) self.clientsock = clientsock def run(self): print "Entering thread prompt loop" clientfile = self.clientsock.makefile('w') filein = self.clientsock.makefile('r') loc = self.clientsock.getsockname() while 1: try: clientfile.write('%s %s >>> ' % loc) clientfile.flush() line = filein.readline() if len(line)==0: raise EOFError,"nothing" #print >>sys.stderr,"got line: " + line if line.strip(): oldout, olderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = clientfile, clientfile try: try: exec compile(line + '\n','<remote pyin>', 'single') except: print_exc() finally: sys.stdout=oldout sys.stderr=olderr clientfile.flush() except EOFError,e: print >>sys.stderr, "connection close, prompt thread returns" break #print >>sys.stdout, "".join(apply(format_exception,sys.exc_info())) self.clientsock.close() prompter = promptagent(clientsock) prompter.start() print "promptagent - thread started"
Python
import os, sys import subprocess if __name__ == '__main__': directory = os.path.dirname(os.path.abspath(sys.argv[0])) script = os.path.join(directory, 'socketserver.py') while 1: cmdlist = ["python", script] cmdlist.extend(sys.argv[1:]) print "starting subcommand:", " ".join(cmdlist) process = subprocess.Popen(cmdlist) process.wait()
Python
#! /usr/bin/env python """ start socket based minimal readline exec server """ # this part of the program only executes on the server side # progname = 'socket_readline_exec_server-1.2' debug = 0 import sys, socket, os try: import fcntl except ImportError: fcntl = None if debug: # and not os.isatty(sys.stdin.fileno()): f = open('/tmp/execnet-socket-pyout.log', 'a', 0) old = sys.stdout, sys.stderr sys.stdout = sys.stderr = f #import py #compile = py.code.compile def exec_from_one_connection(serversock): print progname, 'Entering Accept loop', serversock.getsockname() clientsock,address = serversock.accept() print progname, 'got new connection from %s %s' % address clientfile = clientsock.makefile('r+',0) print "reading line" # rstrip so that we can use \r\n for telnet testing source = clientfile.readline().rstrip() clientfile.close() g = {'clientsock' : clientsock, 'address' : address} source = eval(source) if source: co = compile(source+'\n', source, 'exec') print progname, 'compiled source, executing' try: exec co in g finally: print progname, 'finished executing code' # background thread might hold a reference to this (!?) #clientsock.close() def bind_and_listen(hostport): if isinstance(hostport, str): host, port = hostport.split(':') hostport = (host, int(port)) serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # set close-on-exec if hasattr(fcntl, 'FD_CLOEXEC'): old = fcntl.fcntl(serversock.fileno(), fcntl.F_GETFD) fcntl.fcntl(serversock.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) # allow the address to be re-used in a reasonable amount of time if os.name == 'posix' and sys.platform != 'cygwin': serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversock.bind(hostport) serversock.listen(5) return serversock def startserver(serversock, loop=False): try: while 1: try: exec_from_one_connection(serversock) except (KeyboardInterrupt, SystemExit): raise except: import traceback traceback.print_exc() if not loop: break finally: print "leaving socketserver execloop" serversock.shutdown(2) if __name__ == '__main__': import sys if len(sys.argv)>1: hostport = sys.argv[1] else: hostport = ':8888' serversock = bind_and_listen(hostport) startserver(serversock, loop=False)
Python
#! /usr/bin/env python """ a remote python shell for injection into startserver.py """ import sys, os, socket, select try: clientsock except NameError: print "client side starting" import sys host, port = sys.argv[1].split(':') port = int(port) myself = open(os.path.abspath(sys.argv[0]), 'rU').read() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(repr(myself)+'\n') print "send boot string" inputlist = [ sock, sys.stdin ] try: while 1: r,w,e = select.select(inputlist, [], []) if sys.stdin in r: line = raw_input() sock.sendall(line + '\n') if sock in r: line = sock.recv(4096) sys.stdout.write(line) sys.stdout.flush() except: import traceback print traceback.print_exc() sys.exit(1) print "server side starting" # server side # from traceback import print_exc from threading import Thread class promptagent(Thread): def __init__(self, clientsock): Thread.__init__(self) self.clientsock = clientsock def run(self): print "Entering thread prompt loop" clientfile = self.clientsock.makefile('w') filein = self.clientsock.makefile('r') loc = self.clientsock.getsockname() while 1: try: clientfile.write('%s %s >>> ' % loc) clientfile.flush() line = filein.readline() if len(line)==0: raise EOFError,"nothing" #print >>sys.stderr,"got line: " + line if line.strip(): oldout, olderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = clientfile, clientfile try: try: exec compile(line + '\n','<remote pyin>', 'single') except: print_exc() finally: sys.stdout=oldout sys.stderr=olderr clientfile.flush() except EOFError,e: print >>sys.stderr, "connection close, prompt thread returns" break #print >>sys.stdout, "".join(apply(format_exception,sys.exc_info())) self.clientsock.close() prompter = promptagent(clientsock) prompter.start() print "promptagent - thread started"
Python
#! /usr/bin/env python """ start socket based minimal readline exec server """ # this part of the program only executes on the server side # progname = 'socket_readline_exec_server-1.2' debug = 0 import sys, socket, os try: import fcntl except ImportError: fcntl = None if debug: # and not os.isatty(sys.stdin.fileno()): f = open('/tmp/execnet-socket-pyout.log', 'a', 0) old = sys.stdout, sys.stderr sys.stdout = sys.stderr = f #import py #compile = py.code.compile def exec_from_one_connection(serversock): print progname, 'Entering Accept loop', serversock.getsockname() clientsock,address = serversock.accept() print progname, 'got new connection from %s %s' % address clientfile = clientsock.makefile('r+',0) print "reading line" # rstrip so that we can use \r\n for telnet testing source = clientfile.readline().rstrip() clientfile.close() g = {'clientsock' : clientsock, 'address' : address} source = eval(source) if source: co = compile(source+'\n', source, 'exec') print progname, 'compiled source, executing' try: exec co in g finally: print progname, 'finished executing code' # background thread might hold a reference to this (!?) #clientsock.close() def bind_and_listen(hostport): if isinstance(hostport, str): host, port = hostport.split(':') hostport = (host, int(port)) serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # set close-on-exec if hasattr(fcntl, 'FD_CLOEXEC'): old = fcntl.fcntl(serversock.fileno(), fcntl.F_GETFD) fcntl.fcntl(serversock.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) # allow the address to be re-used in a reasonable amount of time if os.name == 'posix' and sys.platform != 'cygwin': serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversock.bind(hostport) serversock.listen(5) return serversock def startserver(serversock, loop=False): try: while 1: try: exec_from_one_connection(serversock) except (KeyboardInterrupt, SystemExit): raise except: import traceback traceback.print_exc() if not loop: break finally: print "leaving socketserver execloop" serversock.shutdown(2) if __name__ == '__main__': import sys if len(sys.argv)>1: hostport = sys.argv[1] else: hostport = ':8888' serversock = bind_and_listen(hostport) startserver(serversock, loop=False)
Python
""" A windows service wrapper for the py.execnet socketserver. To use, run: python socketserverservice.py register net start ExecNetSocketServer """ import sys import os import time import win32serviceutil import win32service import win32event import win32evtlogutil import servicemanager import threading import socketserver appname = 'ExecNetSocketServer' class SocketServerService(win32serviceutil.ServiceFramework): _svc_name_ = appname _svc_display_name_ = "%s" % appname _svc_deps_ = ["EventLog"] def __init__(self, args): # The exe-file has messages for the Event Log Viewer. # Register the exe-file as event source. # # Probably it would be better if this is done at installation time, # so that it also could be removed if the service is uninstalled. # Unfortunately it cannot be done in the 'if __name__ == "__main__"' # block below, because the 'frozen' exe-file does not run this code. # win32evtlogutil.AddSourceToRegistry(self._svc_display_name_, servicemanager.__file__, "Application") win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.WAIT_TIME = 1000 # in milliseconds def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # Redirect stdout and stderr to prevent "IOError: [Errno 9] # Bad file descriptor". Windows services don't have functional # output streams. sys.stdout = sys.stderr = open('nul', 'w') # Write a 'started' event to the event log... win32evtlogutil.ReportEvent(self._svc_display_name_, servicemanager.PYS_SERVICE_STARTED, 0, # category servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) print "Begin: %s" % (self._svc_display_name_) hostport = ':8888' print 'Starting py.execnet SocketServer on %s' % hostport serversock = socketserver.bind_and_listen(hostport) thread = threading.Thread(target=socketserver.startserver, args=(serversock,), kwargs={'loop':True}) thread.setDaemon(True) thread.start() # wait to be stopped or self.WAIT_TIME to pass while True: result = win32event.WaitForSingleObject(self.hWaitStop, self.WAIT_TIME) if result == win32event.WAIT_OBJECT_0: break # write a 'stopped' event to the event log. win32evtlogutil.ReportEvent(self._svc_display_name_, servicemanager.PYS_SERVICE_STOPPED, 0, # category servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) print "End: %s" % appname if __name__ == '__main__': # Note that this code will not be run in the 'frozen' exe-file!!! win32serviceutil.HandleCommandLine(SocketServerService)
Python
""" send a "quit" signal to a remote server """ import sys import socket hostport = sys.argv[1] host, port = hostport.split(':') hostport = (host, int(port)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(hostport) sock.sendall('"raise KeyboardInterrupt"\n')
Python
import rlcompleter2 rlcompleter2.setup() import register, sys try: hostport = sys.argv[1] except: hostport = ':8888' gw = register.ServerGateway(hostport)
Python
import os, inspect, socket import sys from py.magic import autopath ; mypath = autopath() import py # the list of modules that must be send to the other side # for bootstrapping gateways # XXX we'd like to have a leaner and meaner bootstrap mechanism startup_modules = [ 'py.__.thread.io', 'py.__.thread.pool', 'py.__.execnet.inputoutput', 'py.__.execnet.gateway', 'py.__.execnet.message', 'py.__.execnet.channel', ] def getsource(dottedname): mod = __import__(dottedname, None, None, ['__doc__']) return inspect.getsource(mod) from py.__.execnet import inputoutput, gateway class InstallableGateway(gateway.Gateway): """ initialize gateways on both sides of a inputoutput object. """ def __init__(self, io): self._remote_bootstrap_gateway(io) super(InstallableGateway, self).__init__(io=io, _startcount=1) def _remote_bootstrap_gateway(self, io, extra=''): """ return Gateway with a asynchronously remotely initialized counterpart Gateway (which may or may not succeed). Note that the other sides gateways starts enumerating its channels with even numbers while the sender gateway starts with odd numbers. This allows to uniquely identify channels across both sides. """ bootstrap = [extra] bootstrap += [getsource(x) for x in startup_modules] bootstrap += [io.server_stmt, "Gateway(io=io, _startcount=2).join(joinexec=False)", ] source = "\n".join(bootstrap) self._trace("sending gateway bootstrap code") io.write('%r\n' % source) class PopenCmdGateway(InstallableGateway): def __init__(self, cmd): infile, outfile = os.popen2(cmd) io = inputoutput.Popen2IO(infile, outfile) super(PopenCmdGateway, self).__init__(io=io) class PopenGateway(PopenCmdGateway): """ This Gateway provides interaction with a newly started python subprocess. """ def __init__(self, python=sys.executable): """ instantiate a gateway to a subprocess started with the given 'python' executable. """ cmd = '%s -u -c "exec input()"' % python super(PopenGateway, self).__init__(cmd) def _remote_bootstrap_gateway(self, io, extra=''): # have the subprocess use the same PYTHONPATH and py lib x = py.path.local(py.__file__).dirpath().dirpath() ppath = os.environ.get('PYTHONPATH', '') plist = [str(x)] + ppath.split(':') s = "\n".join([extra, "import sys ; sys.path[:0] = %r" % (plist,), "import os ; os.environ['PYTHONPATH'] = %r" % ppath, str(py.code.Source(stdouterrin_setnull)), "stdouterrin_setnull()", "" ]) super(PopenGateway, self)._remote_bootstrap_gateway(io, s) class SocketGateway(InstallableGateway): """ This Gateway provides interaction with a remote process by connecting to a specified socket. On the remote side you need to manually start a small script (py/execnet/script/socketserver.py) that accepts SocketGateway connections. """ def __init__(self, host, port): """ instantiate a gateway to a process accessed via a host/port specified socket. """ self.host = host = str(host) self.port = port = int(port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) io = inputoutput.SocketIO(sock) super(SocketGateway, self).__init__(io=io) self.remoteaddress = '%s:%d' % (self.host, self.port) def new_remote(cls, gateway, hostport=None): """ return a new (connected) socket gateway, instatiated indirectly through the given 'gateway'. """ if hostport is None: host, port = ('', 0) # XXX works on all platforms? else: host, port = hostport socketserverbootstrap = py.code.Source( mypath.dirpath('script', 'socketserver.py').read('rU'), """ import socket sock = bind_and_listen((%r, %r)) port = sock.getsockname() channel.send(port) startserver(sock) """ % (host, port) ) # execute the above socketserverbootstrap on the other side channel = gateway.remote_exec(socketserverbootstrap) (realhost, realport) = channel.receive() #gateway._trace("new_remote received" # "port=%r, hostname = %r" %(realport, hostname)) return py.execnet.SocketGateway(host, realport) new_remote = classmethod(new_remote) class SshGateway(PopenCmdGateway): """ This Gateway provides interaction with a remote process, established via the 'ssh' command line binary. The remote side needs to have a Python interpreter executable. """ def __init__(self, sshaddress, remotepython='python', identity=None): """ instantiate a remote ssh process with the given 'sshaddress' and remotepython version. you may specify an 'identity' filepath. """ self.remoteaddress = sshaddress remotecmd = '%s -u -c "exec input()"' % (remotepython,) cmdline = [sshaddress, remotecmd] # XXX Unix style quoting for i in range(len(cmdline)): cmdline[i] = "'" + cmdline[i].replace("'", "'\\''") + "'" cmd = 'ssh -C' if identity is not None: cmd += ' -i %s' % (identity,) cmdline.insert(0, cmd) super(SshGateway, self).__init__(' '.join(cmdline)) def _remote_bootstrap_gateway(self, io, s=""): extra = "\n".join([ str(py.code.Source(stdouterrin_setnull)), "stdouterrin_setnull()", s, ]) super(SshGateway, self)._remote_bootstrap_gateway(io, extra) def stdouterrin_setnull(): """ redirect file descriptors 0 and 1 (and possibly 2) to /dev/null. note that this function may run remotely without py lib support. """ # complete confusion (this is independent from the sys.stdout # and sys.stderr redirection that gateway.remote_exec() can do) # note that we redirect fd 2 on win too, since for some reason that # blocks there, while it works (sending to stderr if possible else # ignoring) on *nix import sys, os try: devnull = os.devnull except AttributeError: if os.name == 'nt': devnull = 'NUL' else: devnull = '/dev/null' # stdin sys.stdin = os.fdopen(os.dup(0), 'rb', 0) fd = os.open(devnull, os.O_RDONLY) os.dup2(fd, 0) os.close(fd) # stdout sys.stdout = os.fdopen(os.dup(1), 'wb', 0) fd = os.open(devnull, os.O_WRONLY) os.dup2(fd, 1) # stderr for win32 if os.name == 'nt': sys.stderr = os.fdopen(os.dup(2), 'wb', 0) os.dup2(fd, 2) os.close(fd)
Python
def f(): import os, stat, shutil, md5 destdir, options = channel.receive() modifiedfiles = [] def remove(path): assert path.startswith(destdir) try: os.unlink(path) except OSError: # assume it's a dir shutil.rmtree(path) def receive_directory_structure(path, relcomponents): try: st = os.lstat(path) except OSError: st = None msg = channel.receive() if isinstance(msg, list): if st and not stat.S_ISDIR(st.st_mode): os.unlink(path) st = None if not st: os.makedirs(path) entrynames = {} for entryname in msg: receive_directory_structure(os.path.join(path, entryname), relcomponents + [entryname]) entrynames[entryname] = True if options.get('delete'): for othername in os.listdir(path): if othername not in entrynames: otherpath = os.path.join(path, othername) remove(otherpath) elif msg is not None: checksum = None if st: if stat.S_ISREG(st.st_mode): msg_mtime, msg_size = msg if msg_size != st.st_size: pass elif msg_mtime != st.st_mtime: f = open(path, 'rb') checksum = md5.md5(f.read()).digest() f.close() else: return # already fine else: remove(path) channel.send(("send", (relcomponents, checksum))) modifiedfiles.append((path, msg)) receive_directory_structure(destdir, []) STRICT_CHECK = False # seems most useful this way for py.test channel.send(("list_done", None)) for path, (time, size) in modifiedfiles: data = channel.receive() channel.send(("ack", path[len(destdir) + 1:])) if data is not None: if STRICT_CHECK and len(data) != size: raise IOError('file modified during rsync: %r' % (path,)) f = open(path, 'wb') f.write(data) f.close() try: os.utime(path, (time, time)) except OSError: pass del data channel.send(("links", None)) msg = channel.receive() while msg is not 42: # we get symlink _type, relpath, linkpoint = msg assert _type == "link" path = os.path.join(destdir, relpath) try: remove(path) except OSError: pass os.symlink(os.path.join(destdir, linkpoint), path) msg = channel.receive() channel.send(("done", None))
Python
#
Python