os.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "pocketpy/pocketpy.h"
  2. #include "pocketpy/common/utils.h"
  3. #include "pocketpy/objects/object.h"
  4. #include "pocketpy/common/sstream.h"
  5. #include "pocketpy/interpreter/vm.h"
  6. #if PY_SYS_PLATFORM == 0
  7. #include <direct.h>
  8. int platform_chdir(const char* path) { return _chdir(path); }
  9. bool platform_getcwd(char* buf, size_t size) { return _getcwd(buf, size) != NULL; }
  10. #elif PY_SYS_PLATFORM == 3 || PY_SYS_PLATFORM == 5
  11. #include <unistd.h>
  12. int platform_chdir(const char* path) { return chdir(path); }
  13. bool platform_getcwd(char* buf, size_t size) { return getcwd(buf, size) != NULL; }
  14. #else
  15. int platform_chdir(const char* path) { return -1; }
  16. bool platform_getcwd(char* buf, size_t size) { return false; }
  17. #endif
  18. static bool os_chdir(int argc, py_Ref argv) {
  19. PY_CHECK_ARGC(1);
  20. PY_CHECK_ARG_TYPE(0, tp_str);
  21. const char* path = py_tostr(py_arg(0));
  22. int code = platform_chdir(path);
  23. if(code != 0) return py_exception(tp_OSError, "chdir() failed: %d", code);
  24. py_newnone(py_retval());
  25. return true;
  26. }
  27. static bool os_getcwd(int argc, py_Ref argv) {
  28. char buf[1024];
  29. if(!platform_getcwd(buf, sizeof(buf))) return py_exception(tp_OSError, "getcwd() failed");
  30. py_newstr(py_retval(), buf);
  31. return true;
  32. }
  33. static bool os_system(int argc, py_Ref argv) {
  34. PY_CHECK_ARGC(1);
  35. PY_CHECK_ARG_TYPE(0, tp_str);
  36. #if PK_IS_DESKTOP_PLATFORM
  37. const char* cmd = py_tostr(py_arg(0));
  38. int code = system(cmd);
  39. py_newint(py_retval(), code);
  40. return true;
  41. #else
  42. return py_exception(tp_OSError, "system() is not supported on this platform");
  43. #endif
  44. }
  45. void pk__add_module_os() {
  46. py_Ref mod = py_newmodule("os");
  47. py_bindfunc(mod, "chdir", os_chdir);
  48. py_bindfunc(mod, "getcwd", os_getcwd);
  49. py_bindfunc(mod, "system", os_system);
  50. }
  51. void pk__add_module_sys() {
  52. py_Ref mod = py_newmodule("sys");
  53. py_newstr(py_emplacedict(mod, py_name("platform")), PY_SYS_PLATFORM_STRING);
  54. py_newstr(py_emplacedict(mod, py_name("version")), PK_VERSION);
  55. py_newlist(py_emplacedict(mod, py_name("argv")));
  56. }