main.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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(
  37. "[%d bit] on %s"
  38. "\n",
  39. (int)(sizeof(void*) * 8),
  40. PY_SYS_PLATFORM_STRING);
  41. printf(
  42. "https://github.com/pocketpy/pocketpy"
  43. "\n");
  44. printf(
  45. "Type \"exit()\" to exit."
  46. "\n");
  47. while(true) {
  48. int size = py_replinput(buf);
  49. assert(size < sizeof(buf));
  50. if(size >= 0) {
  51. if(!py_exec2(buf, "<stdin>", REPL_MODE)) py_printexc();
  52. }
  53. }
  54. } else {
  55. char* source = read_file(argv[1]);
  56. if(source) {
  57. if(!py_exec(source)) py_printexc();
  58. free(source);
  59. }
  60. }
  61. py_finalize();
  62. return 0;
  63. }