main.c 1.8 KB

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