Python ast.parse方法代碼示例,ast.parse用法. ... 需要導入模塊: import ast [as 別名] # 或者: from ast import parse [as 別名] def ast(self) -> ast.
當前位置:首頁>>代碼示例>>Python>>正文
本文整理匯總了Python中ast.parse方法的典型用法代碼示例。
如果您正苦於以下問題:Pythonast.parse方法的具體用法?Pythonast.parse怎麽用?Pythonast.parse使用的例子?那麽恭喜您,這裏精選的方法代碼示例或許可以為您提供幫助。
您也可以進一步了解該方法所在類ast的用法示例。
在下文中一共展示了ast.parse方法的20個代碼示例,這些例子默認根據受歡迎程度排序。
您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。
示例1:ast
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defast(self)->ast.Module:#type:ignore
"""AbstractSyntaxTree(AST)representationofthesource_file.
Thisiscachedlocallyandupdatedifthesource_fileischanged.
Returns:
ParsedASTforthesourcefile.
Raises:
TypeError:if``source_file``isnotset.
"""
ifself._astisNone:
ifnotself.source_file:
raiseTypeError("Source_filepropertyissettoNoneType.")
withopen(self.source_file,"rb")assrc_stream:
self._ast=ast.parse(src_stream.read())
returnself._ast開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:20,代碼來源:api.py
示例2:_format_traceback_frame
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def_format_traceback_frame(self,io,tb):#type:(IO,...)->Tuple[Any]
frame_info=inspect.getframeinfo(tb)
filename=frame_info.filename
lineno=frame_info.lineno
function=frame_info.function
line=frame_info.code_context[0]
stripped_line=line.lstrip("")
try:
tree=ast.parse(stripped_line,mode="exec")
formatted=self._format_tree(tree,stripped_line,io)
formatted=(len(line)-len(stripped_line))*""+formatted
exceptSyntaxError:
formatted=line
return(
io.format("{}".format(filename)),
"{}>".format(lineno)ifnotPY2elselineno,
"{}".format(function),
formatted,
)開發者ID:sdispater,項目名稱:clikit,代碼行數:23,代碼來源:exception_trace.py
示例3:load_test_cases
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defload_test_cases():
base_path=os.path.dirname(__file__)
test_case_path=os.path.join(base_path,"test_cases")
test_case_files=os.listdir(test_case_path)
test_cases=[]
forfnameintest_case_files:
ifnotfname.endswith(".py"):
continue
fullpath=os.path.join(test_case_path,fname)
data=open(fullpath).read()
tree=ast.parse(data,fullpath)
codes,messages=extract_expected_errors(data)
test_cases.append((tree,fullpath,codes,messages))
returntest_cases開發者ID:graphql-python,項目名稱:gql,代碼行數:21,代碼來源:test_flake8_linter.py
示例4:get_top_imported_names
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defget_top_imported_names(file:str)->Set[str]:
"""Collectnamesimportedingivenfile.
Weonlycollecttop-levelnames,i.e.`fromfoo.barimportbaz`
willonlyadd`foo`tothelist.
"""
ifnotfile.endswith(".pyi"):
returnset()
withopen(os.path.join(file),"rb")asf:
content=f.read()
parsed=ast.parse(content)
top_imported=set()
fornodeinast.walk(parsed):
ifisinstance(node,ast.Import):
fornameinnode.names:
top_imported.add(name.name.split('.')[0])
elifisinstance(node,ast.ImportFrom):
ifnode.level>0:
#Relativeimportsalwaysrefertothecurrentpackage.
continue
assertnode.module
top_imported.add(node.module.split('.')[0])
returntop_imported開發者ID:python,項目名稱:typeshed,代碼行數:25,代碼來源:migrate_script.py
示例5:_inferWaiter
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def_inferWaiter(gen):
f=gen.gi_frame
s=inspect.getsource(f)
s=_dedent(s)
root=ast.parse(s)
root.symdict=f.f_globals.copy()
root.symdict.update(f.f_locals)
#printast.dump(root)
v=_YieldVisitor(root)
v.visit(root)
ifv.kind==_kind.EDGE_TUPLE:
return_EdgeTupleWaiter(gen)
ifv.kind==_kind.SIGNAL_TUPLE:
return_SignalTupleWaiter(gen)
ifv.kind==_kind.DELAY:
return_DelayWaiter(gen)
ifv.kind==_kind.EDGE:
return_EdgeWaiter(gen)
ifv.kind==_kind.SIGNAL:
return_SignalWaiter(gen)
#default
return_Waiter(gen)開發者ID:myhdl,項目名稱:myhdl,代碼行數:24,代碼來源:_Waiter.py
示例6:_makeAST
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def_makeAST(f):
#Needtolookattheflagsusedtocompiletheoriginalfunctionfand
#passthesesameflagstothecompile()function.Thisensuresthat
#syntax-changing__future__importslikeprint_functionworkcorrectly.
orig_f_co_flags=f.__code__.co_flags
#co_flagscancontainvariousinternalflagsthatwecan'tpassto
#compile(),sostripthemouthere
valid_flags=0
forfuture_featurein__future__.all_feature_names:
feature=getattr(__future__,future_feature)
valid_flags|=feature.compiler_flag
s=inspect.getsource(f)
s=_dedent(s)
#usecompileinsteadofast.parsesothatadditionalflagscanbepassed
flags=ast.PyCF_ONLY_AST|(orig_f_co_flags&valid_flags)
tree=compile(s,filename='',mode='exec',
flags=flags,dont_inherit=True)
#tree=ast.parse(s)
tree.sourcefile=inspect.getsourcefile(f)
tree.lineoffset=inspect.getsourcelines(f)[1]-1
returntree開發者ID:myhdl,項目名稱:myhdl,代碼行數:23,代碼來源:_util.py
示例7:compile_expression
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defcompile_expression(exp):
cached=cache.get(exp)
ifcachedisnotNone:
returncached
_exp=ast.parse(exp)
nodes=[nodefornodeinast.walk(_exp)]
iflen(nodes)<2ornotisinstance(nodes[1],ast.Expr):
raiseExpressionError("%sisnotExpression"%exp)
fornodeinnodes:
ifisinstance(node,ast.Call):
raiseExpressionError("Callmethodisforbidden")
ifisinstance(node,ast.Lambda):
raiseExpressionError("Lambdaisstronglyforbidden")
result=compile(exp,'',mode='eval')
cache[exp]=result
returnresult開發者ID:moira-alert,項目名稱:worker,代碼行數:18,代碼來源:expression.py
示例8:explodeCode
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defexplodeCode(string):
lines=string.splitlines()
total=len(lines)
iftotal==0:
return[None,None]
a=ast.parse(string)
forms=[]
totalForms=len(a.body)
foriinrange(totalForms):
start=a.body[i].lineno
ifi>=totalForms-1:
end=total
else:
end=a.body[i+1].lineno-1
forms.append(toForm(lines,{"start":start,"end":end}))
returnforms開發者ID:LightTable,項目名稱:Python,代碼行數:18,代碼來源:ltmain.py
示例9:_grab_ast
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def_grab_ast(repo,abspath):
"""ParsesthePythonfileindicatedby`abspath`.
Args:
*repo(RecipeRepo)-Therepowhichcontains`abspath`.Usedforerror
reporting.
*abspath(str)-Theabsolute(native)pathtothePythonfiletoparse.
ReturnsthePythonASTobjectifthefileexistsandisparsable.Otherwise
logsanerrorandreturnsNone.
"""
assertisinstance(repo,RecipeRepo),type(repo)
relpath=os.path.relpath(abspath,repo.path)
assert'..'notinrelpath
try:
withopen(abspath,'rb')asf:
returnast.parse(f.read(),relpath)
exceptSyntaxErrorasex:
LOGGER.warn('skipping%s:badsyntax:%s',_to_posix(relpath),ex)
exceptOSErrorasex:
LOGGER.warn('skipping%s:%s',_to_posix(relpath),ex)
returnNone開發者ID:luci,項目名稱:recipes-py,代碼行數:24,代碼來源:cmd.py
示例10:parse_parameter
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defparse_parameter(param):
"""ParsesarecipeparameterintoaDoc.Parameter.
Args:
*param(recipe_api.Property)-Theparametertoparse.
ReturnsDoc.Parameter.
"""
assertisinstance(param,recipe_api.Property),type(param)
default=None
ifparam._defaultisnotrecipe_api.PROPERTY_SENTINEL:
default=json.dumps(param._default)
returndoc.Doc.Parameter(
docstring=param.help,
kind=param.kind.schema_proto()ifparam.kindelseNone,
default_json=default)開發者ID:luci,項目名稱:recipes-py,代碼行數:19,代碼來源:cmd.py
示例11:compile_ast
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defcompile_ast(self,source,filename="",symbol="single"):
#Here,wetrytocompiletherelevantcode.Itmaythrowan
#exceptionindicatingthatthecommandisnotcomplete,in
#whichcasewecannotproceed,butafullcommandwillbe
#suppliedeventually.
compiled=code.compile_command(source,filename,symbol)
#Ifthecompilationsucceeded,asindicatedbyitsobjectnotbeing
#None,andnoexceptionhavingoccurred,parseitwithASTand
#storethat.
ifcompiled!=None:
self.latest_parsed=ast.parse(source,filename,symbol)
CaptureExprs().visit(self.latest_parsed)
#Sincelatest_parsedhasbeenalteredtocapturevaluescomputed
#butnotassigned,storeanunalteredcopyfortesting.
self.clean_parsed=ast.parse(source,filename,symbol)
returncompile(self.latest_parsed,filename,symbol)開發者ID:alexander-bauer,項目名稱:swirlypy,代碼行數:19,代碼來源:Recording.py
示例12:mi_parameters
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defmi_parameters(code,count_multi=True):
'''Givenasourcecodesnippet,computethenecessaryparametersto
computetheMaintainabilityIndexmetric.Theseinclude:
*theHalsteadVolume
*theCyclomaticComplexity
*thenumberofLLOC(LogicalLinesofCode)
*thepercentoflinesofcomment
:parammulti:IfTrue,thencountmultilinestringsascommentlinesas
well.ThisisnotalwayssafebecausePythonmultilinestringsarenot
alwaysdocstrings.
'''
ast_node=ast.parse(code)
raw=analyze(code)
comments_lines=raw.comments+(raw.multiifcount_multielse0)
comments=comments_lines/float(raw.sloc)*100ifraw.sloc!=0else0
return(h_visit_ast(ast_node).volume,
ComplexityVisitor.from_ast(ast_node).total_complexity,raw.lloc,
comments)開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:22,代碼來源:metrics.py
示例13:easy_debug
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defeasy_debug(code:str,should_exec=False,ctx=None):
res=to_tagged_ast(parse(code).result)
c=py_compile(res)
print("-----------code")
print(code)
print("-----------Python")
print(dis.dis(code))
print("-----------YaPyPy")
print(dis.dis(c))
print("-----------astpretty")
astpretty.pprint(ast.parse(code))
print("-----------Pythonexecresult")
exec(code,ctxor{})
print("-----------YaPyPyexecresult")
ifshould_exec:
exec(c,ctxor{})
else:
print("\t(skip)")開發者ID:Xython,項目名稱:YAPyPy,代碼行數:20,代碼來源:easy_debug.py
示例14:test_warning_calls
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
deftest_warning_calls():
#combined"ignore"andstacklevelerror
base=Path(numpy.__file__).parent
forpathinbase.rglob("*.py"):
ifbase/"testing"inpath.parents:
continue
ifpath==base/"__init__.py":
continue
ifpath==base/"random"/"__init__.py":
continue
#usetokenizetoauto-detectencodingonsystemswhereno
#defaultencodingisdefined(e.g.LANG='C')
withtokenize.open(str(path))asfile:
tree=ast.parse(file.read())
FindFuncs(path).visit(tree)開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:test_warnings.py
示例15:evaluate
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defevaluate(self,node,filename=None):
"""
Evaluateasourcestringornode,using``filename``when
displayingerrors.
"""
ifisinstance(node,string_types):
self.source=node
kwargs={'mode':'eval'}
iffilename:
kwargs['filename']=filename
try:
node=ast.parse(node,**kwargs)
exceptSyntaxErrorase:
s=self.get_fragment(e.offset)
raiseSyntaxError('syntaxerror%s'%s)
node_type=node.__class__.__name__.lower()
handler=self.get_handler(node_type)
ifhandlerisNone:
ifself.sourceisNone:
s='(sourcenotavailable)'
else:
s=self.get_fragment(node.col_offset)
raiseSyntaxError("don'tknowhowtoevaluate%r%s"%(
node_type,s))
returnhandler(node)開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:markers.py
示例16:_get_modules
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def_get_modules(self,content)->Set[str]:
imports=set()
tree=ast.parse(content)
fornodeinast.walk(tree):
ifisinstance(node,ast.Import):
forsubnodeinnode.names:
imports.add(subnode.name)
elifisinstance(node,ast.ImportFrom)andnode.level==0:
imports.add(node.module)
modules=set()
formoduleinimports:
ifnotmodule:
continue
module=module.split('.',maxsplit=1)[0]
ifmoduleinself.stdlib:
continue
module=self.aliases.get(module,module)
modules.add(module)
returnmodules開發者ID:dephell,項目名稱:dephell,代碼行數:21,代碼來源:imports.py
示例17:__init__
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def__init__(self,agenda):
"""Createincludefromargument.
Args:
agenda(str,Agenda):ArgumenttotheINCLUDEstatement.Thiscan
eitherbeastringoranAgendaobject.
"""
iftype(agenda)==str:
ifnotagendainimports:
self.agenda=Agenda.parse(agenda)
imports[agenda]=self.agenda
else:
self.agenda=imports[agenda]
eliftype(agenda)==Agenda:
self.agenda=agenda
else:
raiseException("agendaargumentmustbeeitheracontrolfile"
"nameoratyphon.arts.workspace.agenda.Agendaobject.")開發者ID:atmtools,項目名稱:typhon,代碼行數:21,代碼來源:workspace.py
示例18:_analyse_ast
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
def_analyse_ast(str_code:str)->Tuple[bool,Set[str]]:
"""
AnalysetheASTbuiltfrom`str_definition`.
Parameters
----------
str_code:str
Astringcontainingapieceofvalidpythoncode:statement,expressionor
functiondefinition(butwithoutthe`def....`line).
Returns
-------
has_return:bool
Trueistheexpressioncontainsatleastonereturnstatement.
variables:Setofstr
Asetcontainingtheidentifiersofallvariablesusedbutnotdeclared
in`str_code`.
"""
node=ast.parse(str_code)
visitor=VarCounterVisitor()
visitor.visit(node)
returnvisitor.has_return,visitor.get_vars()開發者ID:Orange-OpenSource,項目名稱:pyDcop,代碼行數:25,代碼來源:expressionfunction.py
示例19:preprocess_method_body
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
defpreprocess_method_body(source_code_obj):
src=inspect.getsource(source_code_obj)
ast_tree=ast.parse(src)
visitor=RewriteDicts()
ast_tree=visitor.visit(ast_tree)
ast.fix_missing_locations(ast_tree)
updated_code=compile(ast_tree,filename='',mode='exec')
bc=Bytecode.from_code(updated_code)
dlist=visitor.updated_dicts
RewriteDicts.updated_dicts=[]
RewriteDicts.last_store_name=None
block_code=get_code_block(bc)
returnblock_code.arg,dlist開發者ID:CityOfZion,項目名稱:neo-boa,代碼行數:21,代碼來源:ast_preprocess.py
示例20:test_afterSubMult
點讚6
#需要導入模塊:importast[as別名]
#或者:fromastimportparse[as別名]
deftest_afterSubMult(self):
'TestsafterSubToMultpre-processing'
tests=[("1+2-3",ast.BoolOp(ast.Add(),[ast.Num(1),ast.Num(2),
ast.BinOp(ast.Num(-1),
ast.Mult(),
ast.Num(3))])),
("1+2-3+4",ast.BoolOp(ast.Add(),
[ast.Num(1),
ast.Num(2),
ast.BinOp(ast.Num(-1),
ast.Mult(),
ast.Num(3)),
ast.Num(4)])),
("(1+2)-(3+4)",
ast.BoolOp(ast.Add(),
[ast.Num(1),ast.Num(2),
ast.BinOp(ast.Num(-1),ast.Mult(),
ast.BinOp(ast.Num(3),ast.Add(),
ast.Num(4)))]))]
forteststring,ref_astintests:
test_ast=ast.parse(teststring,mode="eval").body
test_ast=pre_processing.all_preprocessings(test_ast)
test_ast=Flattening(ast.Add).visit(test_ast)
self.assertTrue(Comparator().visit(test_ast,ref_ast))開發者ID:quarkslab,項目名稱:sspam,代碼行數:27,代碼來源:test_flattening.py
注:本文中的ast.parse方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。