• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python yacc.parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中yacc.parse函数的典型用法代码示例。如果您正苦于以下问题:Python parse函数的具体用法?Python parse怎么用?Python parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: parseInput

 def parseInput(self):
     if self.__haveSerialPort:        
         waitingCount = self.__ser.inWaiting()
         #waitingCount = 1
         if waitingCount == 0:
             return
         x = self.__ser.read(waitingCount)
         self.parseStr += x
     else:
         self.parseStr = ' <OK> '
     while len(self.parseStr) >= 1:
         #print "before:", self.parseStr
         foundEndTokenIndex = self.parseStr.find(">")
         if foundEndTokenIndex != -1:
             # Found '>' token delimiter
             newTokenString = self.parseStr[:foundEndTokenIndex+1]
             foundBeginTokenIndex = newTokenString.rfind("<")
             if foundBeginTokenIndex != -1 and foundBeginTokenIndex < foundEndTokenIndex:
                 yaccInput = newTokenString[foundBeginTokenIndex:]
                 if yaccInput != '<OK>':
                     print "yacc:", yaccInput
                 currentToken = 0
                 yacc.parse(yaccInput, debug=1)
             # Remove up to end of token from string
             self.parseStr = self.parseStr[foundEndTokenIndex+1:]
             #print "after:", self.parseStr
         else:
             break
开发者ID:GarethS,项目名称:Motor,代码行数:28,代码来源:transfer.py


示例2: parse

def parse(formula):
    """Alias for yacc.parse.

    This function is used as method of the 'class' parse (this module).

    """
    return yacc.parse(formula)
开发者ID:radical-software,项目名称:radicalspam,代码行数:7,代码来源:parse.py


示例3: mk_rpn_query

def mk_rpn_query (query):
    tmp = tree_to_q (yacc.parse (query))
    if isinstance (tmp[0], asn1.OidVal): # XXX yuck, bad style
        attrset = tmp [0]
        tmp = tmp [1]
    else:
        attrset = z3950.bib1
    rpnq = z3950.RPNQuery (attributeSet = attrset)
    rpnq.rpn = tmp
    return ('type-1', rpnq)
开发者ID:snac-cooperative,项目名称:cheshire,代码行数:10,代码来源:ccl.py


示例4: parse

def parse(string):
    lex.lex()
    yacc.yacc()
    rules = yacc.parse(string)

    result = []
    while rules:
        current = rules.pop(0)
        result.extend(current[1])
    return(result)
开发者ID:jbjorne,项目名称:CVSTransferTest,代码行数:10,代码来源:convertrule.py


示例5: test

def test (s, fn):
    ast = yacc.parse (s)
    ctx = Ctx ()
    print "### Auto-generated at %s from %s" % (
        time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()),
        fn)
    print "import rpchelp"
    tmp = ast.to_str (ctx)
    print ctx.finish ()
    print tmp
开发者ID:mayli,项目名称:pinefs,代码行数:10,代码来源:rpcgen.py


示例6: parse

 def parse(self, query, operator):
     
     try:
         return yacc.parse( query )
     except QueryParserError:
         raise 
     except:
         import traceback
         traceback.print_exc()
         raise QueryParserError, 'parser failed for query: %s' % query
开发者ID:eaudeweb,项目名称:naaya,代码行数:10,代码来源:PyQueryParser.py


示例7: read_configuration

def read_configuration(filename):
    try:
        file = open(filename)
    except:
        print "Failed opening checkpoint file '%s'" % filename
        raise Exception
    try:
        return yacc.parse(string.join(file.readlines()))
    except Exception, msg:
        print "Failed parsing checkpoint file '%s'" % filename
        print "Error: %s" % msg
        sys.exit(1)
开发者ID:Albermg7,项目名称:flexus,代码行数:12,代码来源:munge-checkpoint.py


示例8: expr

def expr(s, p, hexadecimal=False):
    global proc
    proc = p

    value, (ptrcount, local, type, size) = yacc.parse(s)
    if hexadecimal:
        if value < 0: # hex asked, negative value: make positive
            value = 256**size+value
        s = hex(value).replace('L','').lower()
    else:
        if value < 0: s = '-'+str(abs(value))
        else: s = str(value)
       
    return (value, s)
开发者ID:embedded-systems,项目名称:qr,代码行数:14,代码来源:cexpr.py


示例9: parseFile

def parseFile(filename):
    """
    This funstion returns a tuple containing a list of opcodes
    and a list of symbols.
    Every opcode is a tuple of the form 
    (commandname, parameter, parameter, ...).
    Every symbol is a tuple of the form (type, name).
    """
    global commands
    global symbols
    commands = []
    symbols = []
    try:
        f = open(filename, "r")
        for line in f.readlines():
            line = line.strip()
            yacc.parse(line)
        f.close()
        result = (commands[:], symbols[:])
        commands = []
        symbols = []
        return result
    except IOError:
        return ()
开发者ID:MBlaureNs,项目名称:graphics-final-project,代码行数:24,代码来源:mdl.py


示例10: _myparse

def _myparse(x, outfile=sys.stdout):
    global _more, _xbuf, _outfile, _last_line
    _outfile = outfile
    _last_line = _xbuf + x
    ret = yacc.parse(_xbuf + x)
    if _more:
        # this takes care of the newline inside of [] and {}. We don't want
        # to have the newline as another token
        _xbuf += x.strip()
        if not _xbuf.endswith(";"):
            _xbuf += ";"
        _more = False
    else:
        _xbuf = ""
        more = False
    return ret
开发者ID:pombredanne,项目名称:ompc,代码行数:16,代码来源:ompcply.py


示例11: mk_rpn_query

def mk_rpn_query (query):
    """Transform a CCL query into an RPN query."""
    # need to copy or create a new lexer because it contains globals
    # PLY 1.0 lacks __copy__
    # PLY 1.3.1-1.5 have __copy__, but it's broken and returns None
    # I sent David Beazley a patch, so future PLY releases will
    # presumably work correctly.
    # Recreating the lexer each time is noticeably slower, so this solution
    # is suboptimal for PLY <= 1.5, but better than being thread-unsafe.
    # Perhaps I should have per-thread lexer instead XXX
    # with example/twisted/test.py set to parse_only, I get 277 parses/sec
    # with fixed PLY, vs. 63 parses/sec with broken PLY, on my 500 MHz PIII
    # laptop.
    
    copiedlexer = None
    if hasattr (lexer, '__copy__'):
        copiedlexer = lexer.__copy__ ()
    if copiedlexer == None:
        copiedlexer = lex.lex ()
    ast = yacc.parse (query, copiedlexer)
    return ast_to_rpn (ast)
开发者ID:JanX2,项目名称:books-macosx,代码行数:21,代码来源:ccl.py


示例12: constr_testing

def constr_testing(value, constr, var_name):
    global names

    lexer = lex.lex()
    parser = yacc.yacc()
    # print parser.parse('ASSERT(NOT(123 = 123))')

    # print constr

    for index, eachvar in enumerate(var_name):
        str_value = []
        for val in value[index]:
            if val != '':
                # TODO: input concrete value must be integer
                str_val = BitArray(uint = int(val), length = 8)
                str_value.append('0x' + str_val.hex)

        names[eachvar] = str_value
    #print names


    return ([constr[0]], yacc.parse(constr[1]))
开发者ID:junxzm1990,项目名称:simulator,代码行数:22,代码来源:cvc_parsing.py


示例13: compute_string

def compute_string(s, debug=False):
    lex.input(s)
    
    if debug:
        while 1:
            tok = lex.token()
            if not tok: break
            if tok.type != 'NEWLINE':
                print "line %d:%s(%s)"%(tok.lineno, tok.type, tok.value)
            else:
                print("line %d:%s(\\n)"%(tok.lineno, tok.type))
    
    result = yacc.parse(s) #, debug=2)
    print result.__class__
    print(explore(result,0))
    print("------------------ End Explore ------------------")
    r = compute(result)
    print("\nResult = %s of type %s" % (r, r.__class__))
    print("\nListing vars")
    for k in vars:
        print("%s:%s:%s" % (k, vars[k].__class__, vars[k]))
    return r
开发者ID:Xitog,项目名称:tallentaa,代码行数:22,代码来源:pypo_interpreter.py


示例14: parseCode

def parseCode(code):
	print "----------------"
	print "PARSING CODE:"
	print "----------------"
	return yacc.parse(code)
开发者ID:TeddyDotNet,项目名称:pyNase,代码行数:5,代码来源:naseParser.py


示例15: get_ast

def get_ast(string):
    ast = yacc.parse(string) #, debug=2)
    return ast
开发者ID:Xitog,项目名称:tallentaa,代码行数:3,代码来源:pypo_interpreter.py


示例16: open

        in_filename = args[0]
        in_file = open(in_filename)

        if len(args) > 1:
            out_file = open_output(args[1])

    del parser

    options.output = out_file

    # Parse the spec
    lex.lex()
    yacc.yacc(debug=0)
    blocks = {}
    unions = {}
    _, block_map, union_map = yacc.parse(in_file.read())
    base_list = [8, 16, 32, 64]
    suffix_map = {8 : 'u8', 16 : 'u16', 32 : 'u32', 64 : 'u64'}
    for base_info, block_list in block_map.items():
        base, base_bits, base_sign_extend = base_info
        for name, b in block_list.items():
            if not base in base_list:
                raise ValueError("Invalid base size: %d" % base)
            suffix = suffix_map[base]
            b.set_base(base, base_bits, base_sign_extend, suffix)
            blocks[name] = b

    symtab = {}
    symtab.update(blocks)
    for base, union_list in union_map.items():
        unions.update(union_list)
开发者ID:cavedweller,项目名称:rust-sel4,代码行数:31,代码来源:bitfield_gen.py


示例17: __str__

        self.Col=Col

    def __str__(self):
        return "Arreglo de Estilos y Arreglo de Expresiones Graficables de Tamanos Diferentes. En linea, "+str(self.Lin)+"; Columna "+str(self.Col)

class e_nonev_num(Exception): ## No evala a Numeros
    def __init__(self,valor,Lin,Col):
        self.valor=valor
        self.Lin=Lin
        self.Col=Col

    def __str__(self):
        return "La expresion del Range no evalua a Numeros. En linea, "+str(self.Lin)+"; Columna "+str(self.Col)

## Constructor del Parser
import yacc
yacc.yacc()

if __name__ == "__main__":

    NM = re.sub(".txt","",sys.argv[1])
    FIL = open(sys.argv[1],"r")

    a =yacc.parse(FIL.read(),tracking=True)

    NEW = open("entrada.pl","w")
    NEW.write("set term pdf\n")
    NEW.write("set output '"+NM+".pdf' \n")
    NEW.write(a)
    
开发者ID:jmtt89,项目名称:Interpretador_GNUplot,代码行数:29,代码来源:fun.py


示例18: isinstance

        return
    for (a, val) in node.__dict__.items ():
        if trace: print "# Testing node ", node, "attr", a, " val", val
        if a[0] == '_':
            continue
        elif isinstance (val, type ([])):
            for v in val:
               calc_dependencies (v, dict, trace)
        elif isinstance (val, Node):
            calc_dependencies (val, dict, trace)


def testlex (s, fn, dict):
    lexer.input (s)
    while 1:
        token = lexer.token ()
        if not token:
            break
        print token

import sys

if __name__ == '__main__':
    defined_dict = {}
    for fn in sys.argv [1:]:
        f = open (fn, "r")
        ast = yacc.parse (f.read())
        print map (str, ast)
        lexer.lineno = 1

开发者ID:rolfschr,项目名称:testerman,代码行数:29,代码来源:compiler.py


示例19: len

    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = [p[1]] + p[2]

def p_error(p):
    print "Syntax error on line %d %s [type=%s]" % (p.lineno, p.value, p.type)
    
import yacc
yacc.yacc()


f = open("all_perms.spt")
txt = f.read()
f.close()

#lex.input(txt)
#while 1:
#    tok = lex.token()
#    if not tok:
#        break
#    print tok

test = "define(`foo',`{ read write append }')"
test2 = """define(`all_filesystem_perms',`{ mount remount unmount getattr relabelfrom relabelto transition associate quotamod quotaget }')
define(`all_security_perms',`{ compute_av compute_create compute_member check_context load_policy compute_relabel compute_user setenforce setbool setsecparam setcheckreqprot }')
"""
result = yacc.parse(txt)
print result
    
开发者ID:DanAlbert,项目名称:selinux,代码行数:29,代码来源:classperms.py


示例20: cvc_translate

def cvc_translate(test_str):
    global names
    names = {}
    return yacc.parse(test_str)
开发者ID:junxzm1990,项目名称:simulator,代码行数:4,代码来源:cvc_to_python.py



注:本文中的yacc.parse函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python yacc.yacc函数代码示例发布时间:2022-05-26
下一篇:
Python extcommunity.ExtCommunity类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap