Python学习笔记 - 做一个缩小版CPython解释器
也不是我自己想做,主要是同学要我帮忙,他想学习Python,但是磁盘剩余空间太小,不够安装Python,就要我帮忙写一个小一点的。
要我写,就肯定要省略这样那样的,不过没关系(反正初学者应该够用了)。
直接上代码。
个人觉得用C语言的话可能编译出来的程序会比较小(反正我的Python环境已经超过1.2GB了,不知道是不是因为模块比较多的原因)
仅供Windows
系统使用。
名称:pyey(Python Everywhere)
#include "Python.h" // Include Python header
#include <windows.h>
#include <stdio.h>
int main (void)(int argc, char *argv [])
{
/*
Usage: pyey script
*/
Py_Initialize(); // Initialize Python parser.
/*
if (argc == 1){ // Run terminal.
system("python.exe");
return 0;
}
*/
// if (argc != 2){ // Bad arguments.
if (argc != 2){ // Bad arguments.
printf("Usage: pyey file\n file: path of Python script.");
return 1;
}
char *path = argv[1]; // Get the path.
PyObject* ex;
ex = PyEval_SimpleString("__import__('os').path.isfile(%s)" % path);
isfile = PyBool_AsInt(ex);
if (!isfile){
printf("No such file: &s", path);
return 1;
}
PyObject* pPath;
pPath = PyUnicode_FromString(path);
PyObject* pMod = NULL;
pMod = PyModule_ImportModule(pPath);
if (pMod == NULL){ // Failed to import
printf("Failed to import module: &s", path);
return 0;
}
/* Run Python module */
Py_Finalize(); // Finalize Python parser.
return 1;
可以使用TDM-GCC
编译。
编者技术有限,如有不足敬请指教!