1
0

main.c 2.3 KB

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