Skip to content

Commit c276357

Browse files
Merge pull request RustPython#961 from palaviv/os-cwd
os.{getcwd,chdir}
2 parents 57e250f + c7e9bdd commit c276357

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

tests/snippets/stdlib_os.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ def __exit__(self, exc_type, exc_val, exc_tb):
6565
pass
6666

6767

68+
class TestWithTempCurrentDir():
69+
def __enter__(self):
70+
self.prev_cwd = os.getcwd()
71+
72+
def __exit__(self, exc_type, exc_val, exc_tb):
73+
os.chdir(self.prev_cwd)
74+
75+
6876
FILE_NAME = "test1"
6977
FILE_NAME2 = "test2"
7078
SYMLINK_FILE = "symlink"
@@ -161,3 +169,8 @@ def __exit__(self, exc_type, exc_val, exc_tb):
161169

162170
assert os.path.basename(fname) == FILE_NAME
163171
assert os.path.dirname(fname) == tmpdir
172+
173+
with TestWithTempCurrentDir():
174+
os.chdir(tmpdir)
175+
assert os.getcwd() == tmpdir
176+
os.path.exists(FILE_NAME)

vm/src/stdlib/os.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,19 @@ fn os_symlink(src: PyStringRef, dst: PyStringRef, vm: &VirtualMachine) -> PyResu
479479
unimplemented!();
480480
}
481481

482+
fn os_getcwd(vm: &VirtualMachine) -> PyResult<String> {
483+
Ok(env::current_dir()
484+
.map_err(|s| vm.new_os_error(s.to_string()))?
485+
.as_path()
486+
.to_str()
487+
.unwrap()
488+
.to_string())
489+
}
490+
491+
fn os_chdir(path: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
492+
env::set_current_dir(&path.value).map_err(|s| vm.new_os_error(s.to_string()))
493+
}
494+
482495
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
483496
let ctx = &vm.ctx;
484497

@@ -534,6 +547,8 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
534547
"stat_result" => stat_result,
535548
"stat" => ctx.new_rustfunc(os_stat),
536549
"symlink" => ctx.new_rustfunc(os_symlink),
550+
"getcwd" => ctx.new_rustfunc(os_getcwd),
551+
"chdir" => ctx.new_rustfunc(os_chdir),
537552
"O_RDONLY" => ctx.new_int(0),
538553
"O_WRONLY" => ctx.new_int(1),
539554
"O_RDWR" => ctx.new_int(2),

0 commit comments

Comments
 (0)