main.c 2.3 KB

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