From dc72796e2c9dd248f50343b5bcb231e12684048e Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Mon, 27 Mar 2023 13:35:59 +0800 Subject: [PATCH] up --- src/io.h | 7 +++++++ src/main.cpp | 23 +++++++++++++++-------- tests/70_file.py | 2 ++ 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/io.h b/src/io.h index cbbef646..549a9c6c 100644 --- a/src/io.h +++ b/src/io.h @@ -88,10 +88,17 @@ void add_module_io(VM* vm){ void add_module_os(VM* vm){ PyVar mod = vm->new_module("os"); + // Working directory is shared by all VMs!! vm->bind_func<0>(mod, "getcwd", [](VM* vm, const Args& args){ return VAR(std::filesystem::current_path().string()); }); + vm->bind_func<1>(mod, "chdir", [](VM* vm, const Args& args){ + std::filesystem::path path(CAST(Str&, args[0]).c_str()); + std::filesystem::current_path(path); + return vm->None; + }); + vm->bind_func<1>(mod, "listdir", [](VM* vm, const Args& args){ std::filesystem::path path(CAST(Str&, args[0]).c_str()); std::filesystem::directory_iterator di; diff --git a/src/main.cpp b/src/main.cpp index bf06ec80..22188639 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,7 @@ #include -#include "pocketpy.h" +#include +#include "pocketpy.h" #ifdef _WIN32 @@ -58,17 +59,23 @@ int main(int argc, char** argv){ } if(argc == 2){ - std::string filename = argv[1]; - if(filename == "-h" || filename == "--help") goto __HELP; + std::string argv_1 = argv[1]; + if(argv_1 == "-h" || argv_1 == "--help") goto __HELP; - std::ifstream file(filename); - if(!file.is_open()){ - std::cerr << "File not found: " << filename << std::endl; + std::filesystem::path filepath(argv[1]); + if(!std::filesystem::exists(filepath)){ + std::cerr << "File not found: " << argv_1 << std::endl; return 1; - } + } + std::ifstream file(filepath); + if(!file.is_open()) return 1; std::string src((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + + // set parent path as cwd + std::filesystem::current_path(filepath.parent_path()); + pkpy::PyVarOrNull ret = nullptr; - ret = vm->exec(src.c_str(), filename, pkpy::EXEC_MODE); + ret = vm->exec(src.c_str(), argv_1, pkpy::EXEC_MODE); pkpy_delete(vm); return ret != nullptr ? 0 : 1; } diff --git a/tests/70_file.py b/tests/70_file.py index 73ff4eaa..d9fdde27 100644 --- a/tests/70_file.py +++ b/tests/70_file.py @@ -18,4 +18,6 @@ with open('123.txt', 'a') as f: with open('123.txt', 'r') as f: assert f.read() == '123456' + '测试' +assert os.path_exists('123.txt') os.remove('123.txt') +assert not os.path_exists('123.txt')