main.c 1.7 KB

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