当前位置:   article > 正文

《python源码剖析》笔记 python环境初始化_py_initialize

py_initialize

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


1.线程环境初始化

Py_InitializeEx,Python会首先调用 PyInterpreterState_New创建一个崭新的PyInterpreterState对象。

创建了PyInterpreterState(进程状态)对象之后,Python会调用PyThreadState_New创建PyThreadState(线程状态)对象

全局变量_PyThreadState_Current维护着当前活动的线程
PyInterpreterState对象中维护着所有的PyThreadState对象共享的资源


2.系统module初始化
Python最终会将interp->modules创建为一个PyDictObject对象,它维护着系统所有的(module名,module对象)的对应关系
创建__builtin__ module

  1. PyObject *
  2. _PyBuiltin_Init(void)
  3. {
  4. PyObject *mod, *dict, *debug;
  5. //[1]:创建并设置__builtin__ module
  6. mod = Py_InitModule4("__builtin__", builtin_methods,
  7. builtin_doc, (PyObject *)NULL,
  8. PYTHON_API_VERSION);
  9. //[2]:将所有Pyton内建类型加入到__builtin__ module中
  10. dict = PyModule_GetDict(mod);
  11. #define SETBUILTIN(NAME, OBJECT) \
  12. if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
  13. return NULL; \
  14. SETBUILTIN("None", Py_None);
  15. SETBUILTIN("Ellipsis", Py_Ellipsis);
  16. SETBUILTIN("NotImplemented", Py_NotImplemented);
  17. SETBUILTIN("False", Py_False);
  18. SETBUILTIN("True", Py_True);
  19. SETBUILTIN("basestring", &PyBaseString_Type);
  20. SETBUILTIN("bool", &PyBool_Type);
  21. SETBUILTIN("memoryview", &PyMemoryView_Type);
  22. SETBUILTIN("bytearray", &PyByteArray_Type);
  23. SETBUILTIN("bytes", &PyString_Type);
  24. SETBUILTIN("buffer", &PyBuffer_Type);
  25. SETBUILTIN("classmethod", &PyClassMethod_Type);
  26. #ifndef WITHOUT_COMPLEX
  27. SETBUILTIN("complex", &PyComplex_Type);
  28. #endif
  29. SETBUILTIN("dict", &PyDict_Type);
  30. SETBUILTIN("enumerate", &PyEnum_Type);
  31. SETBUILTIN("file", &PyFile_Type);
  32. SETBUILTIN("float", &PyFloat_Type);
  33. SETBUILTIN("frozenset", &PyFrozenSet_Type);
  34. SETBUILTIN("property", &PyProperty_Type);
  35. SETBUILTIN("int", &PyInt_Type);
  36. SETBUILTIN("list", &PyList_Type);
  37. SETBUILTIN("long", &PyLong_Type);
  38. SETBUILTIN("object", &PyBaseObject_Type);
  39. SETBUILTIN("reversed", &PyReversed_Type);
  40. SETBUILTIN("set", &PySet_Type);
  41. SETBUILTIN("slice", &PySlice_Type);
  42. SETBUILTIN("staticmethod", &PyStaticMethod_Type);
  43. SETBUILTIN("str", &PyString_Type);
  44. SETBUILTIN("super", &PySuper_Type);
  45. SETBUILTIN("tuple", &PyTuple_Type);
  46. SETBUILTIN("type", &PyType_Type);
  47. SETBUILTIN("xrange", &PyRange_Type);
  48. #ifdef Py_USING_UNICODE
  49. SETBUILTIN("unicode", &PyUnicode_Type);
  50. #endif
  51. return mod;
  52. #undef SETBUILTIN
  53. }
  1. static PyMethodDef builtin_methods[] = {
  2. {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
  3. {"abs", builtin_abs, METH_O, abs_doc},
  4. {"all", builtin_all, METH_O, all_doc},
  5. {"any", builtin_any, METH_O, any_doc},
  6. {"apply", builtin_apply, METH_VARARGS, apply_doc},
  7. {"bin", builtin_bin, METH_O, bin_doc},
  8. {"callable", builtin_callable, METH_O, callable_doc},
  9. {"chr", builtin_chr, METH_VARARGS, chr_doc},
  10. {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
  11. {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
  12. {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
  13. {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
  14. {"dir", builtin_dir, METH_VARARGS, dir_doc},
  15. {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
  16. {"eval", builtin_eval, METH_VARARGS, eval_doc},
  17. {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
  18. {"filter", builtin_filter, METH_VARARGS, filter_doc},
  19. {"format", builtin_format, METH_VARARGS, format_doc},
  20. {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
  21. {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
  22. {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
  23. {"hash", builtin_hash, METH_O, hash_doc},
  24. {"hex", builtin_hex, METH_O, hex_doc},
  25. {"id", builtin_id, METH_O, id_doc},
  26. {"input", builtin_input, METH_VARARGS, input_doc},
  27. {"intern", builtin_intern, METH_VARARGS, intern_doc},
  28. {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
  29. {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
  30. {"iter", builtin_iter, METH_VARARGS, iter_doc},
  31. {"len", builtin_len, METH_O, len_doc},
  32. {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
  33. {"map", builtin_map, METH_VARARGS, map_doc},
  34. {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
  35. {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
  36. {"next", builtin_next, METH_VARARGS, next_doc},
  37. {"oct", builtin_oct, METH_O, oct_doc},
  38. {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
  39. {"ord", builtin_ord, METH_O, ord_doc},
  40. {"pow", builtin_pow, METH_VARARGS, pow_doc},
  41. {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
  42. {"range", builtin_range, METH_VARARGS, range_doc},
  43. {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
  44. {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
  45. {"reload", builtin_reload, METH_O, reload_doc},
  46. {"repr", builtin_repr, METH_O, repr_doc},
  47. {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
  48. {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
  49. {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
  50. {"sum", builtin_sum, METH_VARARGS, sum_doc},
  51. #ifdef Py_USING_UNICODE
  52. {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
  53. #endif
  54. {"vars", builtin_vars, METH_VARARGS, vars_doc},
  55. {"zip", builtin_zip, METH_VARARGS, zip_doc},
  56. {NULL, NULL},
  57. };


创建sys module
Python在创建并设置了__builtin__ module之后,会用同样的流程设置sys module,并像设置
interp->builtins一样设置interp->sysdict


创建__main__ module
  1. static void
  2. initmain(void)
  3. {
  4. PyObject *m, *d;
  5. //[1]:创建 __main__ module,并将其插入 interp-modules中
  6. m = PyImport_AddModule("__main__");
  7. //[2]:获得 __main__ module 中的dict
  8. d = PyModule_GetDict(m);
  9. if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  10. //[3]:获得interp->modules中的 __builtin__ module
  11. PyObject *bimod = PyImport_ImportModule("__builtin__");
  12. //[4]:将("__builtin__", __builtin__ module) 插入到 __main__ module 的dict中
  13. PyDict_SetItemString(d, "__builtins__", bimod);
  14. }
  15. }

单元测试
if __name__ == "__main__"

设置site-specific的module的搜索路径
site.py
1.将site-packages路径加入到sys.path中
2.将site-packages目录下的所有.pth文件中的所有路径加入到sys.path中


3.激活Python虚拟机
先编译Python语句获得抽象语法树
再获得<module __main__>中维护的dict作为当前活动的frame对象的local名字空间 global名字空间
交互方式运行和脚本文件方式运行最终都会进行run_mode函数,然后启动虚拟机 
  1. static PyObject *
  2. run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
  3. PyCompilerFlags *flags, PyArena *arena)
  4. {
  5. PyCodeObject *co;
  6. PyObject *v;
  7. //[1]:基于AST编译字节码指令序列,创建PyCodeObject对象
  8. co = PyAST_Compile(mod, filename, flags, arena);
  9. //[2]:创建PyFrameObject对象,执行PyCodeObject对象中的字节码指令序列
  10. v = PyEval_EvalCode(co, globals, locals);
  11. Py_DECREF(co);
  12. return v;
  13. }

创建PyCodeObject对象--> PyEval_EvalCode执行PyCodeObject对象中的字节码-->创建PyFrameObject-->PyEval_EvalFrameEx在PyFrameObject上下文环境中执行PyCodeObject对的字节码

名字空间
  1. PyFrameObject *
  2. PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
  3. PyObject *locals)
  4. {
  5. PyFrameObject *back = tstate->frame;
  6. PyFrameObject *f;
  7. PyObject *builtins;
  8. Py_ssize_t i;
  9. //[1]:设置builtin名字空间
  10. if (back == NULL || back->f_globals != globals) {
  11. builtins = PyDict_GetItem(globals, builtin_object);
  12. }
  13. else {
  14. builtins = back->f_builtins;
  15. }
  16. f->f_builtins = builtins;
  17. f->f_back = back;
  18. //[2]:设置global名字空间
  19. f->f_globals = globals;
  20. //[3]:设置local名字空间
  21. if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
  22. (CO_NEWLOCALS | CO_OPTIMIZED))
  23. ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
  24. else if (code->co_flags & CO_NEWLOCALS) {
  25. locals = PyDict_New();
  26. f->f_locals = locals;
  27. }
  28. else {
  29. if (locals == NULL)
  30. locals = globals;//一般情况下,locals和globals指向形同的dict
  31. }
  32. return f;
  33. }

Python所有的线程都共享同样的builtin名字空间
在激活Python字节码虚拟机时,local名字空间和global名字空间一样都被设置成了 __main__ module中的dict

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号