Python 내장 함수 compile()

3343 단어

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)


소스를 코드나AST 대상으로 컴파일하면 컴파일된 코드나 대상은 함수exec(),eval()에 의해 실행될 수 있습니다.

설명


일반 문자열, 바이트 문자열 또는 Abstract Syntax Trees 객체일 수 있는 매개 변수 source.동적 실행이 필요한 코드 세그먼트입니다.
파라미터 filename, 코드 파일 이름, 파일에서 코드를 읽지 않으면 식별할 수 있는 값을 전달합니다.source 인자가 들어왔을 때 filename 인자는 빈 문자를 입력하면 됩니다.
매개 변수 모드, 컴파일 코드의 종류를 지정합니다. 코드의 종류는'exec','eval','single'세 가지가 있습니다.source가 프로세스 문장을 포함할 때mode는'exec'로 지정해야 한다.source가 단일 표현식만 포함할 때 모델은'eval'로 지정해야 한다.source가 상호작용 명령문을 포함하면mode는'single'로 지정됩니다.

예제

>>> cc = 'for i in range(0, 5): print(i)'
>>> com = compile(cc, '', 'exec')
>>> exec(com)
0
1
2
3
4
>>> cc = '2 + 3'
>>> com = compile(cc, '', 'eval')
>>> eval(com)
5
>>> cc = 'name = input("please input your name:")'
>>> com = compile(cc, '', 'single')
>>> exec(com)
please input your name:tim
>>> name
'tim'
>>> 


The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file ('' is commonly used).
The mode argument specifies what kind of code must be compiled; it can be 'exec' if source consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).
The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile() .
If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the future statements in effect around the call to compile are ignored.
Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag attribute on the _Feature instance in the future module. The argument optimize specifies the optimization level of the compiler; the default value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; debug is true), 1 (asserts are removed, debug is false) or 2 (docstrings are removed too). This function raises SyntaxError if the compiled source is invalid, and ValueError if the source contains null bytes. If you want to parse Python code into its AST representation, see ast.parse() .
Note When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

좋은 웹페이지 즐겨찾기