main.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. #else
  10. // set ctrl+c handler
  11. #include <signal.h>
  12. #include <unistd.h>
  13. static void sigint_handler(int sig) { py_interrupt(); }
  14. #endif
  15. char* read_file(const char* path) {
  16. FILE* file = fopen(path, "rb");
  17. if(file == NULL) {
  18. printf("Error: file not found\n");
  19. return NULL;
  20. }
  21. fseek(file, 0, SEEK_END);
  22. long size = ftell(file);
  23. fseek(file, 0, SEEK_SET);
  24. char* buffer = malloc(size + 1);
  25. size = fread(buffer, 1, size, file);
  26. buffer[size] = 0;
  27. return buffer;
  28. }
  29. static char buf[2048];
  30. int main(int argc, char** argv) {
  31. #if _WIN32
  32. SetConsoleCP(CP_UTF8);
  33. SetConsoleOutputCP(CP_UTF8);
  34. #else
  35. signal(SIGINT, sigint_handler);
  36. #endif
  37. if(argc > 2) {
  38. printf("Usage: pocketpy [filename]\n");
  39. return 0;
  40. }
  41. py_initialize();
  42. py_sys_setargv(argc, argv);
  43. if(argc == 1) {
  44. printf("pocketpy " PK_VERSION " (" __DATE__ ", " __TIME__ ") ");
  45. printf("[%d bit] on %s", (int)(sizeof(void*) * 8), PY_SYS_PLATFORM_STRING);
  46. #ifndef NDEBUG
  47. printf(" (DEBUG)");
  48. #endif
  49. printf("\n");
  50. printf("https://github.com/pocketpy/pocketpy\n");
  51. printf("Type \"exit()\" to exit.\n");
  52. while(true) {
  53. int size = py_replinput(buf, sizeof(buf));
  54. if(size == -1) { // Ctrl-D (i.e. EOF)
  55. printf("\n");
  56. break;
  57. }
  58. assert(size < sizeof(buf));
  59. if(size >= 0) {
  60. py_StackRef p0 = py_peek(0);
  61. if(!py_exec(buf, "<stdin>", SINGLE_MODE, NULL)) {
  62. py_printexc();
  63. py_clearexc(p0);
  64. }
  65. }
  66. }
  67. } else {
  68. char* source = read_file(argv[1]);
  69. if(source) {
  70. if(!py_exec(source, argv[1], EXEC_MODE, NULL)) py_printexc();
  71. free(source);
  72. }
  73. }
  74. int code = py_checkexc(false) ? 1 : 0;
  75. py_finalize();
  76. return code;
  77. }