main.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include "pocketpy.h"
  5. #ifdef _WIN32
  6. #define WIN32_LEAN_AND_MEAN
  7. #include <windows.h>
  8. #endif
  9. char* read_file(const char* path) {
  10. FILE* file = fopen(path, "rb");
  11. if(file == NULL) {
  12. printf("Error: file not found\n");
  13. return NULL;
  14. }
  15. fseek(file, 0, SEEK_END);
  16. long size = ftell(file);
  17. fseek(file, 0, SEEK_SET);
  18. char* buffer = malloc(size + 1);
  19. size = fread(buffer, 1, size, file);
  20. buffer[size] = 0;
  21. return buffer;
  22. }
  23. static char buf[2048];
  24. int main(int argc, char** argv) {
  25. #if _WIN32
  26. SetConsoleCP(CP_UTF8);
  27. SetConsoleOutputCP(CP_UTF8);
  28. #endif
  29. if(argc > 2) {
  30. printf("Usage: pocketpy [filename]\n");
  31. return 0;
  32. }
  33. py_initialize();
  34. py_sys_setargv(argc, argv);
  35. if(argc == 1) {
  36. printf("pocketpy " PK_VERSION " (" __DATE__ ", " __TIME__ ") ");
  37. printf("[%d bit] on %s", (int)(sizeof(void*) * 8), PY_SYS_PLATFORM_STRING);
  38. #if PK_DEBUG
  39. printf(" (DEBUG)");
  40. #endif
  41. printf("\n");
  42. printf("https://github.com/pocketpy/pocketpy\n");
  43. printf("Type \"exit()\" to exit.\n");
  44. while(true) {
  45. int size = py_replinput(buf, sizeof(buf));
  46. assert(size < sizeof(buf));
  47. if(size >= 0) {
  48. py_StackRef p0 = py_peek(0);
  49. if(!py_exec(buf, "<stdin>", SINGLE_MODE, NULL)) {
  50. py_printexc();
  51. py_clearexc(p0);
  52. }
  53. }
  54. }
  55. } else {
  56. char* source = read_file(argv[1]);
  57. if(source) {
  58. if(!py_exec(source, argv[1], EXEC_MODE, NULL)) py_printexc();
  59. free(source);
  60. }
  61. }
  62. int code = py_checkexc(false) ? 1 : 0;
  63. py_finalize();
  64. return code;
  65. }