A camada de nível muito alto¶
As funções neste capítulo permitirão que você execute um código-fonte Python fornecido em um arquivo ou buffer, mas não permitirão que você interaja de forma mais detalhada com o interpretador.
Several of these functions accept a start symbol from the grammar as a
parameter. The available start symbols are Py_eval_input
,
Py_file_input
, and Py_single_input
. These are described
following the functions which accept them as parameters.
Note also that several of these functions take FILE*
parameters. One
particular issue which needs to be handled carefully is that the FILE
structure for different C libraries can be different and incompatible. Under
Windows (at least), it is possible for dynamically linked extensions to actually
use different libraries, so care should be taken that FILE*
parameters
are only passed to these functions if it is certain that they were created by
the same library that the Python runtime is using.
-
int
Py_Main
(int argc, wchar_t **argv)¶ The main program for the standard interpreter. This is made available for programs which embed Python. The argc and argv parameters should be prepared exactly as those which are passed to a C program’s
main()
function (converted to wchar_t according to the user’s locale). It is important to note that the argument list may be modified (but the contents of the strings pointed to by the argument list are not). The return value will be0
if the interpreter exits normally (i.e., without an exception),1
if the interpreter exits due to an exception, or2
if the parameter list does not represent a valid Python command line.Note that if an otherwise unhandled
SystemExit
is raised, this function will not return1
, but exit the process, as long asPy_InspectFlag
is not set.
-
int
Py_BytesMain
(int argc, char **argv)¶ Similar to
Py_Main()
but argv is an array of bytes strings.Novo na versão 3.8.
-
int
PyRun_AnyFile
(FILE *fp, const char *filename)¶ Esta é uma interface simplificada para
PyRun_AnyFileExFlags()
abaixo, deixando closeit definido como0
e flags definido comoNULL
.
-
int
PyRun_AnyFileFlags
(FILE *fp, const char *filename, PyCompilerFlags *flags)¶ Esta é uma interface simplificada para
PyRun_AnyFileExFlags()
abaixo, deixando o argumento closeit definido como0
.
-
int
PyRun_AnyFileEx
(FILE *fp, const char *filename, int closeit)¶ Esta é uma interface simplificada para
PyRun_AnyFileExFlags()
abaixo, deixando o argumento flags definido comoNULL
.
-
int
PyRun_AnyFileExFlags
(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)¶ Se fp se referir a um arquivo associado a um dispositivo interativo (entrada de console ou terminal ou pseudo-terminal Unix), retorna o valor de
PyRun_InteractiveLoop()
, caso contrário, retorna o resultado dePyRun_SimpleFile()
. filename é decodificado da codificação do sistema de arquivos (sys.getfilesystemencoding()
). Se filename forNULL
, esta função usa"???"
como o nome do arquivo. Se closeit for true, o arquivo será fechado antes dePyRun_SimpleFileExFlags()
retornar.
-
int
PyRun_SimpleString
(const char *command)¶ This is a simplified interface to
PyRun_SimpleStringFlags()
below, leaving thePyCompilerFlags
* argument set toNULL
.
-
int
PyRun_SimpleStringFlags
(const char *command, PyCompilerFlags *flags)¶ Executa o código-fonte Python de command no módulo
__main__
de acordo com o argumento flags. Se__main__
ainda não existir, ele será criado. Retorna0
em caso de sucesso ou-1
se uma exceção foi gerada. Se houve um erro, não há como obter as informações da exceção. Para o significado de flags, veja abaixo.Note that if an otherwise unhandled
SystemExit
is raised, this function will not return-1
, but exit the process, as long asPy_InspectFlag
is not set.
-
int
PyRun_SimpleFile
(FILE *fp, const char *filename)¶ Esta é uma interface simplificada para
PyRun_SimpleFileExFlags()
abaixo, deixando closeit definido como0
e flags definido comoNULL
.
-
int
PyRun_SimpleFileEx
(FILE *fp, const char *filename, int closeit)¶ Esta é uma interface simplificada para
PyRun_SimpleFileExFlags()
abaixo, deixando o flags definido comoNULL
.
-
int
PyRun_SimpleFileExFlags
(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)¶ Similar to
PyRun_SimpleStringFlags()
, but the Python source code is read from fp instead of an in-memory string. filename should be the name of the file, it is decoded from the filesystem encoding (sys.getfilesystemencoding()
). If closeit is true, the file is closed before PyRun_SimpleFileExFlags returns.Nota
No Windows, fp deve ser aberto como modo binário (por exemplo,
fopen(filename, "rb")
). Caso contrário, o Python pode não manipular corretamente o arquivo de script com final de linha LF.
-
int
PyRun_InteractiveOne
(FILE *fp, const char *filename)¶ Esta é uma interface simplificada para
PyRun_InteractiveOneFlags()
abaixo, deixando flags definido comoNULL
.
-
int
PyRun_InteractiveOneFlags
(FILE *fp, const char *filename, PyCompilerFlags *flags)¶ Read and execute a single statement from a file associated with an interactive device according to the flags argument. The user will be prompted using
sys.ps1
andsys.ps2
. filename is decoded from the filesystem encoding (sys.getfilesystemencoding()
).Retorna
0
quando a entrada foi executada com sucesso,-1
se houve uma exceção ou um código de erro do arquivo de inclusãoerrcode.h
distribuído como parte do Python se houve um erro de análise. (Observe queerrcode.h
não é incluído porPython.h
, então deve ser incluído especificamente se necessário.)
-
int
PyRun_InteractiveLoop
(FILE *fp, const char *filename)¶ Esta é uma interface simplificada para
PyRun_InteractiveLoopFlags()
abaixo, deixando flags definido comoNULL
.
-
int
PyRun_InteractiveLoopFlags
(FILE *fp, const char *filename, PyCompilerFlags *flags)¶ Read and execute statements from a file associated with an interactive device until EOF is reached. The user will be prompted using
sys.ps1
andsys.ps2
. filename is decoded from the filesystem encoding (sys.getfilesystemencoding()
). Returns0
at EOF or a negative number upon failure.
-
int
(*PyOS_InputHook)
(void)¶ Pode ser definido para apontar para uma função com o protótipo
int func(void)
. A função será chamada quando o prompt do interpretador do Python estiver prestes a ficar ocioso e aguardar a entrada do usuário no terminal. O valor de retorno é ignorado. A substituição deste hook pode ser usada para integrar o prompt do interpretador com outros laços de eventos, como feito emModules/_tkinter.c
no código-fonte do Python.
-
char*
(*PyOS_ReadlineFunctionPointer)
(FILE *, FILE *, const char *)¶ Pode ser definido para apontar para uma função com o protótipo
char *func(FILE *stdin, FILE *stdout, char *prompt)
, substituindo a função padrão usada para ler uma única linha de entrada no prompt do interpretador. Espera-se que a função produza a string prompt se não forNULL
e, em seguida, leia uma linha de entrada do arquivo de entrada padrão fornecido, retornando a string resultante. Por exemplo, o móduloreadline
define este gancho para fornecer recursos de edição de linha e preenchimento de tabulação.O resultado deve ser uma string alocada por
PyMem_RawMalloc()
ouPyMem_RawRealloc()
, ouNULL
se ocorrer um erro.Alterado na versão 3.4: O resultado deve ser alocado por
PyMem_RawMalloc()
ouPyMem_RawRealloc()
, em vez de ser alocado porPyMem_Malloc()
ouPyMem_Realloc()
.
-
struct _node*
PyParser_SimpleParseString
(const char *str, int start)¶ This is a simplified interface to
PyParser_SimpleParseStringFlagsFilename()
below, leaving filename set toNULL
and flags set to0
.Deprecated since version 3.9, will be removed in version 3.10.
-
struct _node*
PyParser_SimpleParseStringFlags
(const char *str, int start, int flags)¶ This is a simplified interface to
PyParser_SimpleParseStringFlagsFilename()
below, leaving filename set toNULL
.Deprecated since version 3.9, will be removed in version 3.10.
-
struct _node*
PyParser_SimpleParseStringFlagsFilename
(const char *str, const char *filename, int start, int flags)¶ Parse Python source code from str using the start token start according to the flags argument. The result can be used to create a code object which can be evaluated efficiently. This is useful if a code fragment must be evaluated many times. filename is decoded from the filesystem encoding (
sys.getfilesystemencoding()
).Deprecated since version 3.9, will be removed in version 3.10.
-
struct _node*
PyParser_SimpleParseFile
(FILE *fp, const char *filename, int start)¶ This is a simplified interface to
PyParser_SimpleParseFileFlags()
below, leaving flags set to0
.Deprecated since version 3.9, will be removed in version 3.10.
-
struct _node*
PyParser_SimpleParseFileFlags
(FILE *fp, const char *filename, int start, int flags)¶ Similar to
PyParser_SimpleParseStringFlagsFilename()
, but the Python source code is read from fp instead of an in-memory string.Deprecated since version 3.9, will be removed in version 3.10.
-
PyObject*
PyRun_String
(const char *str, int start, PyObject *globals, PyObject *locals)¶ - Return value: New reference.
Esta é uma interface simplificada para
PyRun_StringFlags()
abaixo, deixando flags definido comoNULL
.
-
PyObject*
PyRun_StringFlags
(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)¶ - Return value: New reference.
Execut o código-fonte Python de str no contexto especificado pelos objetos globals e locals com os sinalizadores do compilador especificados por flags. globals deve ser um dicionário; locals pode ser qualquer objeto que implemente o protocolo de mapeamento. O parâmetro start especifica o token de início que deve ser usado para analisar o código-fonte.
Retorna o resultado da execução do código como um objeto Python, ou
NULL
se uma exceção foi levantada.
-
PyObject*
PyRun_File
(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)¶ - Return value: New reference.
Esta é uma interface simplificada para
PyRun_FileExFlags()
abaixo, deixando closeit definido como0
e flags definido comoNULL
.
-
PyObject*
PyRun_FileEx
(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit)¶ - Return value: New reference.
Esta é uma interface simplificada para
PyRun_FileExFlags()
abaixo, deixando flags definido comoNULL
.
-
PyObject*
PyRun_FileFlags
(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)¶ - Return value: New reference.
Esta é uma interface simplificada para
PyRun_FileExFlags()
abaixo, deixando closeit definido como0
.
-
PyObject*
PyRun_FileExFlags
(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags)¶ - Return value: New reference.
Similar to
PyRun_StringFlags()
, but the Python source code is read from fp instead of an in-memory string. filename should be the name of the file, it is decoded from the filesystem encoding (sys.getfilesystemencoding()
). If closeit is true, the file is closed beforePyRun_FileExFlags()
returns.
-
PyObject*
Py_CompileString
(const char *str, const char *filename, int start)¶ - Return value: New reference.
Esta é uma interface simplificada para
Py_CompileStringFlags()
abaixo, deixando flags definido comoNULL
.
-
PyObject*
Py_CompileStringFlags
(const char *str, const char *filename, int start, PyCompilerFlags *flags)¶ - Return value: New reference.
Esta é uma interface simplificada para
Py_CompileStringExFlags()
abaixo, com optimize definido como-1
.
-
PyObject*
Py_CompileStringObject
(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize)¶ - Return value: New reference.
Parse and compile the Python source code in str, returning the resulting code object. The start token is given by start; this can be used to constrain the code which can be compiled and should be
Py_eval_input
,Py_file_input
, orPy_single_input
. The filename specified by filename is used to construct the code object and may appear in tracebacks orSyntaxError
exception messages. This returnsNULL
if the code cannot be parsed or compiled.O inteiro optimize especifica o nível de otimização do compilador; um valor de
-1
seleciona o nível de otimização do interpretador dado pela opção-O
. Níveis explícitos são0
(nenhuma otimização;__debug__
é verdadeiro),1
(instruçõesassert
são removidas,__debug__
é falso) ou2
(strings de documentação também são removidas).Novo na versão 3.4.
-
PyObject*
Py_CompileStringExFlags
(const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize)¶ - Return value: New reference.
Like
Py_CompileStringObject()
, but filename is a byte string decoded from the filesystem encoding (os.fsdecode()
).Novo na versão 3.2.
-
PyObject*
PyEval_EvalCode
(PyObject *co, PyObject *globals, PyObject *locals)¶ - Return value: New reference.
Esta é uma interface simplificada para
PyEval_EvalCodeEx()
, com apenas o objeto código e variáveis locais e globais. Os outros argumentos são definidos comoNULL
.
-
PyObject*
PyEval_EvalCodeEx
(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int defcount, PyObject *kwdefs, PyObject *closure)¶ - Return value: New reference.
Avalia um objeto código pré-compilado, dado um ambiente particular para sua avaliação. Este ambiente consiste em um dicionário de variáveis globais, um objeto mapeamento de variáveis locais, vetores de argumentos, nomeados e padrões, um dicionário de valores padrões para argumentos somente-nomeados e uma tupla de clausura de células.
-
PyFrameObject
¶ The C structure of the objects used to describe frame objects. The fields of this type are subject to change at any time.
-
PyObject*
PyEval_EvalFrame
(PyFrameObject *f)¶ - Return value: New reference.
Avalia um quadro de execução. Esta é uma interface simplificada para
PyEval_EvalFrameEx()
, para retrocompatibilidade.
-
PyObject*
PyEval_EvalFrameEx
(PyFrameObject *f, int throwflag)¶ - Return value: New reference.
Esta é a função principal e sem retoques da interpretação Python. O objeto código associado ao quadro de execução f é executado, interpretando bytecode e executando chamadas conforme necessário. O parâmetro adicional throwflag pode ser ignorado na maioria das vezes - se verdadeiro, ele faz com que uma exceção seja levantada imediatamente; isso é usado para os métodos
throw()
de objetos geradores.Alterado na versão 3.4: Essa função agora inclui uma asserção de depuração para ajudar a garantir que ela não descarte silenciosamente uma exceção ativa.
-
int
PyEval_MergeCompilerFlags
(PyCompilerFlags *cf)¶ Esta função altera os sinalizadores do quadro de avaliação atual e retorna verdadeiro em caso de sucesso e falso em caso de falha.
-
int
Py_eval_input
¶ O símbolo inicial da gramática Python para expressões isoladas; para uso com
Py_CompileString()
.
-
int
Py_file_input
¶ O símbolo de início da gramática Python para sequências de instruções conforme lidas de um arquivo ou outra fonte; para uso com
Py_CompileString()
. Este é o símbolo a ser usado ao compilar código-fonte Python arbitrariamente longo.
-
int
Py_single_input
¶ O símbolo de início da gramática Python para uma única declaração; para uso com
Py_CompileString()
. Este é o símbolo usado para o laço do interpretador interativo.
-
struct
PyCompilerFlags
¶ Esta é a estrutura usada para manter os sinalizadores do compilador. Em casos onde o código está apenas sendo compilado, ele é passado como
int flags
, e em casos onde o código está sendo executado, ele é passado comoPyCompilerFlags *flags
. Neste caso,from __future__ import
pode modificar flags.Whenever
PyCompilerFlags *flags
isNULL
,cf_flags
is treated as equal to0
, and any modification due tofrom __future__ import
is discarded.-
int
cf_flags
¶ Sinalizadores do compilador.
-
int
cf_feature_version
¶ cf_feature_version é a versão secundária do Python. Deve ser inicializada como
PY_MINOR_VERSION
.The field is ignored by default, it is used if and only if
PyCF_ONLY_AST
flag is set in cf_flags.
Alterado na versão 3.8: Adicionado campo cf_feature_version.
-
int