os.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. void pk__add_module_os() {
  34. py_Ref mod = py_newmodule("os");
  35. py_bindfunc(mod, "chdir", os_chdir);
  36. py_bindfunc(mod, "getcwd", os_getcwd);
  37. }