codeop — Скомпілюйте код Python

Вихідний код: Lib/codeop.py


Модуль codeop надає утиліти, за допомогою яких можна емулювати цикл читання-оцінки-друку Python, як це робиться в модулі code. У результаті ви, ймовірно, не захочете використовувати модуль безпосередньо; якщо ви хочете включити такий цикл у свою програму, ви, ймовірно, захочете використовувати замість нього модуль code.

У цій роботі є дві частини:

  1. Being able to tell if a line of input completes a Python statement: in short, telling whether to print „>>>“ or „...“ next.

  2. Remembering which future statements the user has entered, so subsequent input can be compiled with these in effect.

Модуль codeop забезпечує спосіб виконання кожної з цих речей, а також спосіб виконання обох.

Щоб зробити лише перше:

codeop.compile_command(source, filename='<input>', symbol='single')

Tries to compile source, which should be a string of Python code and return a code object if source is valid Python code. In that case, the filename attribute of the code object will be filename, which defaults to '<input>'. Returns None if source is not valid Python code, but is a prefix of valid Python code.

Якщо є проблема з source, буде створено виняток. SyntaxError виникає, якщо є недійсний синтаксис Python, і OverflowError або ValueError, якщо є недійсний літерал.

The symbol argument determines whether source is compiled as a statement ('single', the default), as a sequence of statement ('exec') or as an expression ('eval'). Any other value will cause ValueError to be raised.

Примітка

Можливо (але малоймовірно), що синтаксичний аналізатор припиняє синтаксичний аналіз із успішним результатом до того, як досягне кінця джерела; у цьому випадку кінцеві символи можуть ігноруватися замість того, щоб викликати помилку. Наприклад, після зворотної скісної риски, за якою слідують два символи нового рядка, може стояти довільне сміття. Це буде виправлено, коли API для аналізатора стане кращим.

class codeop.Compile

Instances of this class have __call__() methods identical in signature to the built-in function compile(), but with the difference that if the instance compiles program text containing a __future__ statement, the instance „remembers“ and compiles all subsequent program texts with the statement in force.

class codeop.CommandCompiler

Instances of this class have __call__() methods identical in signature to compile_command(); the difference is that if the instance compiles program text containing a __future__ statement, the instance „remembers“ and compiles all subsequent program texts with the statement in force.