📄 pythonrun.c
字号:
/* Portions Copyright (c) 2005 Nokia Corporation */
/* Python interpreter top-level routines, including init/exit */
#include "Python.h"
#include "grammar.h"
#include "node.h"
#include "token.h"
#include "parsetok.h"
#include "errcode.h"
#include "compile.h"
#include "symtable.h"
#include "eval.h"
#include "marshal.h"
#include "object.h"
#include "sliceobject.h"
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#ifdef MS_WIN32
#undef BYTE
#include "windows.h"
#endif
#ifdef macintosh
#include "macglue.h"
#endif
extern char *Py_GetPath(void);
extern const grammar _PyParser_Grammar; /* From graminit.c */
/* Forward */
static void initmain(void);
static void initsite(void);
static PyObject *run_err_node(node *, char *, PyObject *, PyObject *,
PyCompilerFlags *);
static PyObject *run_node(node *, char *, PyObject *, PyObject *,
PyCompilerFlags *);
static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *,
PyCompilerFlags *);
static void err_input(perrdetail *);
static void initsigs(void);
static void call_sys_exitfunc(void);
static void call_ll_exitfuncs(void);
#ifdef Py_TRACE_REFS
int _Py_AskYesNo(char *prompt);
#endif
extern void _PyUnicode_Init(void);
extern void _PyUnicode_Fini(void);
extern void _PyCodecRegistry_Init(void);
extern void _PyCodecRegistry_Fini(void);
#ifndef SYMBIAN
int Py_DebugFlag; /* Needed by parser.c */
int Py_VerboseFlag; /* Needed by import.c */
int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
int Py_NoSiteFlag; /* Suppress 'import site' */
int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
int Py_FrozenFlag; /* Needed by getpath.c */
int Py_UnicodeFlag = 0; /* Needed by compile.c */
int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
#endif
/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
true divisions (which they will be in 2.3). */
#ifndef SYMBIAN
int _Py_QnewFlag = 0;
#endif
#ifndef SYMBIAN
static int initialized = 0;
#else
#define initialized (PYTHON_GLOBALS->initialized)
#endif
/* API to access the initialized flag -- useful for esoteric use */
DL_EXPORT(int)
Py_IsInitialized(void)
{
return initialized;
}
/* Global initializations. Can be undone by Py_Finalize(). Don't
call this twice without an intervening Py_Finalize() call. When
initializations fail, a fatal error is issued and the function does
not return. On return, the first thread and interpreter state have
been created.
Locking: you must hold the interpreter lock while calling this.
(If the lock has not yet been initialized, that's equivalent to
having the lock, but you cannot use multiple threads.)
*/
static int
add_flag(int flag, const char *envs)
{
int env = atoi(envs);
if (flag < env)
flag = env;
if (flag < 1)
flag = 1;
return flag;
}
DL_EXPORT (void)
Py_Initialize(void)
{
PyInterpreterState *interp;
PyThreadState *tstate;
PyObject *bimod, *sysmod;
char *p;
extern void _Py_ReadyTypes(void);
if (initialized)
return;
initialized = 1;
if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Py_DebugFlag = add_flag(Py_DebugFlag, p);
if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
interp = PyInterpreterState_New();
if (interp == NULL)
Py_FatalError("Py_Initialize: can't make first interpreter");
tstate = PyThreadState_New(interp);
if (tstate == NULL)
Py_FatalError("Py_Initialize: can't make first thread");
(void) PyThreadState_Swap(tstate);
_Py_ReadyTypes();
interp->modules = PyDict_New();
if (interp->modules == NULL)
Py_FatalError("Py_Initialize: can't make modules dictionary");
/* Init codec registry */
_PyCodecRegistry_Init();
#ifdef Py_USING_UNICODE
/* Init Unicode implementation; relies on the codec registry */
_PyUnicode_Init();
#endif
bimod = _PyBuiltin_Init();
if (bimod == NULL)
Py_FatalError("Py_Initialize: can't initialize __builtin__");
interp->builtins = PyModule_GetDict(bimod);
Py_INCREF(interp->builtins);
sysmod = _PySys_Init();
if (sysmod == NULL)
Py_FatalError("Py_Initialize: can't initialize sys");
interp->sysdict = PyModule_GetDict(sysmod);
Py_INCREF(interp->sysdict);
_PyImport_FixupExtension("sys", "sys");
PySys_SetPath(Py_GetPath());
PyDict_SetItemString(interp->sysdict, "modules",
interp->modules);
_PyImport_Init();
/* initialize builtin exceptions */
_PyExc_Init();
_PyImport_FixupExtension("exceptions", "exceptions");
/* phase 2 of builtins */
_PyImport_FixupExtension("__builtin__", "__builtin__");
initsigs(); /* Signal handling stuff, including initintr() */
initmain(); /* Module __main__ */
if (!Py_NoSiteFlag)
initsite(); /* Module site */
}
#ifdef COUNT_ALLOCS
extern void dump_counts(void);
#endif
/* Undo the effect of Py_Initialize().
Beware: if multiple interpreter and/or thread states exist, these
are not wiped out; only the current thread and interpreter state
are deleted. But since everything else is deleted, those other
interpreter and thread states should no longer be used.
(XXX We should do better, e.g. wipe out all interpreters and
threads.)
Locking: as above.
*/
DL_EXPORT (void)
Py_Finalize(void)
{
PyInterpreterState *interp;
PyThreadState *tstate;
if (!initialized)
return;
/* The interpreter is still entirely intact at this point, and the
* exit funcs may be relying on that. In particular, if some thread
* or exit func is still waiting to do an import, the import machinery
* expects Py_IsInitialized() to return true. So don't say the
* interpreter is uninitialized until after the exit funcs have run.
* Note that Threading.py uses an exit func to do a join on all the
* threads created thru it, so this also protects pending imports in
* the threads created via Threading.
*/
call_sys_exitfunc();
initialized = 0;
/* Get current thread state and interpreter pointer */
tstate = PyThreadState_Get();
interp = tstate->interp;
/* Disable signal handling */
PyOS_FiniInterrupts();
/* Cleanup Codec registry */
_PyCodecRegistry_Fini();
/* Destroy all modules */
PyImport_Cleanup();
/* Destroy the database used by _PyImport_{Fixup,Find}Extension */
_PyImport_Fini();
/* Debugging stuff */
#ifdef COUNT_ALLOCS
dump_counts();
#endif
#ifdef Py_REF_DEBUG
fprintf(stderr, "[%ld refs]\n", _Py_RefTotal);
#endif
#ifdef Py_TRACE_REFS
if (Py_GETENV("PYTHONDUMPREFS")) {
_Py_PrintReferences(stderr);
}
#endif /* Py_TRACE_REFS */
/* Now we decref the exception classes. After this point nothing
can raise an exception. That's okay, because each Fini() method
below has been checked to make sure no exceptions are ever
raised.
*/
_PyExc_Fini();
/* Delete current thread */
PyInterpreterState_Clear(interp);
PyThreadState_Swap(NULL);
PyInterpreterState_Delete(interp);
PyMethod_Fini();
PyFrame_Fini();
PyCFunction_Fini();
PyTuple_Fini();
PyString_Fini();
PyInt_Fini();
PyFloat_Fini();
#ifdef Py_USING_UNICODE
/* Cleanup Unicode implementation */
_PyUnicode_Fini();
#endif
/* XXX Still allocated:
- various static ad-hoc pointers to interned strings
- int and float free list blocks
- whatever various modules and libraries allocate
*/
#ifndef SYMBIAN
PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
#endif
call_ll_exitfuncs();
#ifdef Py_TRACE_REFS
_Py_ResetReferences();
#endif /* Py_TRACE_REFS */
}
/* Create and initialize a new interpreter and thread, and return the
new thread. This requires that Py_Initialize() has been called
first.
Unsuccessful initialization yields a NULL pointer. Note that *no*
exception information is available even in this case -- the
exception information is held in the thread, and there is no
thread.
Locking: as above.
*/
DL_EXPORT(PyThreadState *)
Py_NewInterpreter(void)
{
PyInterpreterState *interp;
PyThreadState *tstate, *save_tstate;
PyObject *bimod, *sysmod;
if (!initialized)
Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
interp = PyInterpreterState_New();
if (interp == NULL)
return NULL;
tstate = PyThreadState_New(interp);
if (tstate == NULL) {
PyInterpreterState_Delete(interp);
return NULL;
}
save_tstate = PyThreadState_Swap(tstate);
/* XXX The following is lax in error checking */
interp->modules = PyDict_New();
bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
if (bimod != NULL) {
interp->builtins = PyModule_GetDict(bimod);
Py_INCREF(interp->builtins);
}
sysmod = _PyImport_FindExtension("sys", "sys");
if (bimod != NULL && sysmod != NULL) {
interp->sysdict = PyModule_GetDict(sysmod);
Py_INCREF(interp->sysdict);
PySys_SetPath(Py_GetPath());
PyDict_SetItemString(interp->sysdict, "modules",
interp->modules);
initmain();
if (!Py_NoSiteFlag)
initsite();
}
if (!PyErr_Occurred())
return tstate;
/* Oops, it didn't work. Undo it all. */
PyErr_Print();
PyThreadState_Clear(tstate);
PyThreadState_Swap(save_tstate);
PyThreadState_Delete(tstate);
PyInterpreterState_Delete(interp);
return NULL;
}
/* Delete an interpreter and its last thread. This requires that the
given thread state is current, that the thread has no remaining
frames, and that it is its interpreter's only remaining thread.
It is a fatal error to violate these constraints.
(Py_Finalize() doesn't have these constraints -- it zaps
everything, regardless.)
Locking: as above.
*/
DL_EXPORT(void)
Py_EndInterpreter(PyThreadState *tstate)
{
PyInterpreterState *interp = tstate->interp;
if (tstate != PyThreadState_Get())
Py_FatalError("Py_EndInterpreter: thread is not current");
if (tstate->frame != NULL)
Py_FatalError("Py_EndInterpreter: thread still has a frame");
if (tstate != interp->tstate_head || tstate->next != NULL)
Py_FatalError("Py_EndInterpreter: not the last thread");
PyImport_Cleanup();
PyInterpreterState_Clear(interp);
PyThreadState_Swap(NULL);
PyInterpreterState_Delete(interp);
}
#ifndef SYMBIAN
static char *progname = "python";
#else
static const char *const progname = "python";
#endif
DL_EXPORT(void)
Py_SetProgramName(char *pn)
{
if (pn && *pn)
#ifdef SYMBIAN
(PYTHON_GLOBALS->programname) = pn;
#else
progname = pn;
#endif
}
DL_EXPORT(char *)
Py_GetProgramName(void)
{
#ifndef SYMBIAN
return progname;
#else
// XXX:CW32
if (!(PYTHON_GLOBALS->programname))
return (char *)progname;
else
return (PYTHON_GLOBALS->programname);
#endif
}
#ifndef SYMBIAN
static char *default_home = NULL;
#else
#define default_home (PYTHON_GLOBALS->default_home)
#endif
DL_EXPORT(void)
Py_SetPythonHome(char *home)
{
default_home = home;
}
DL_EXPORT(char *)
Py_GetPythonHome(void)
{
char *home = default_home;
if (home == NULL && !Py_IgnoreEnvironmentFlag)
home = Py_GETENV("PYTHONHOME");
return home;
}
/* Create __main__ module */
static void
initmain(void)
{
PyObject *m, *d;
m = PyImport_AddModule("__main__");
if (m == NULL)
Py_FatalError("can't create __main__ module");
d = PyModule_GetDict(m);
if (PyDict_GetItemString(d, "__builtins__") == NULL) {
PyObject *bimod = PyImport_ImportModule("__builtin__");
if (bimod == NULL ||
PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Py_FatalError("can't add __builtins__ to __main__");
Py_DECREF(bimod);
}
}
/* Import the site module (not into __main__ though) */
static void
initsite(void)
{
PyObject *m, *f;
m = PyImport_ImportModule("site");
if (m == NULL) {
f = PySys_GetObject("stderr");
if (Py_VerboseFlag) {
PyFile_WriteString(
"'import site' failed; traceback:\n", f);
PyErr_Print();
}
else {
PyFile_WriteString(
"'import site' failed; use -v for traceback\n", f);
PyErr_Clear();
}
}
else {
Py_DECREF(m);
}
}
/* Parse input from a file and execute it */
DL_EXPORT(int)
PyRun_AnyFile(FILE *fp, char *filename)
{
return PyRun_AnyFileExFlags(fp, filename, 0, NULL);
}
DL_EXPORT(int)
PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags)
{
return PyRun_AnyFileExFlags(fp, filename, 0, flags);
}
DL_EXPORT(int)
PyRun_AnyFileEx(FILE *fp, char *filename, int closeit)
{
return PyRun_AnyFileExFlags(fp, filename, closeit, NULL);
}
DL_EXPORT(int)
PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit,
PyCompilerFlags *flags)
{
if (filename == NULL)
filename = "???";
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -