main.c 1.5 KB

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