main.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, "r");
  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. 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. if(argc == 1) {
  35. printf("pocketpy " PK_VERSION " (" __DATE__ ", " __TIME__ ") ");
  36. printf("[%d bit] on %s\n", (int)(sizeof(void*) * 8), PY_SYS_PLATFORM_STRING);
  37. printf("https://github.com/pocketpy/pocketpy\n");
  38. printf("Type \"exit()\" to exit.\n");
  39. while(true) {
  40. int size = py_replinput(buf);
  41. assert(size < sizeof(buf));
  42. if(size >= 0) {
  43. if(!py_exec(buf, "<stdin>", REPL_MODE, NULL)) py_printexc();
  44. }
  45. }
  46. } else {
  47. char* source = read_file(argv[1]);
  48. if(source) {
  49. if(!py_exec(source, argv[1], EXEC_MODE, NULL)) py_printexc();
  50. free(source);
  51. }
  52. }
  53. int code = py_checkexc() ? 1 : 0;
  54. py_finalize();
  55. return code;
  56. }