Ben Chuanlong Du's Blog

It is never too late to learn.

Current Working Directory in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips and Traps

  1. Notice std::env::current_dir gets the directory path from where you run the Rust application. It might be different from the path of the Rust executable.
In [2]:
use std::env;
In [3]:
std::env::current_dir()
Out[3]:
Ok("/workdir/archives/blog/misc/content/2021/05")
In [5]:
std::env::current_exe()
Out[5]:
Ok("/root/.cargo/bin/evcxr_jupyter")
In [7]:
std::env::set_current_dir("/workdir")
Out[7]:
Ok(())
In [8]:
std::env::current_dir()
Out[8]:
Ok("/workdir")
In [17]:
for var in std::env::vars() {
    println!("{:?}", var);
}
("EVCXR_IS_RUNTIME", "1")
("HOME", "/home/dclong")
("JAVA_HOME", "/usr/lib/jvm/java-8-openjdk-amd64")
("JPY_API_TOKEN", "967da4b8a66e4f5c8ca3aa31833aad0d")
("JPY_PARENT_PID", "70")
("JUPYTERHUB_ACTIVITY_URL", "http://127.0.0.1:8081/hub/api/users/dclong/activity")
("JUPYTERHUB_ADMIN_ACCESS", "1")
("JUPYTERHUB_API_TOKEN", "967da4b8a66e4f5c8ca3aa31833aad0d")
("JUPYTERHUB_API_URL", "http://127.0.0.1:8081/hub/api")
("JUPYTERHUB_BASE_URL", "/")
("JUPYTERHUB_CLIENT_ID", "jupyterhub-user-dclong")
("JUPYTERHUB_HOST", "")
("JUPYTERHUB_OAUTH_CALLBACK_URL", "/user/dclong/oauth_callback")
("JUPYTERHUB_SERVER_NAME", "")
("JUPYTERHUB_SERVICE_PREFIX", "/user/dclong/")
("JUPYTERHUB_USER", "dclong")
("LANG", "en_US.UTF-8")
("LC_ALL", "en_US.UTF-8")
("M2_HOME", "/usr/share/maven")
("PATH", "/opt/pyenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-8-openjdk-amd64/bin")
("RUST_BACKTRACE", "1")
("SHELL", "/bin/bash")
("USER", "dclong")
Out[17]:
()
In [14]:
std::env::var("PATH")
Out[14]:
Ok("/opt/pyenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-8-openjdk-amd64/bin")
In [26]:
std::env::set_var("NIMA", "1000");
In [27]:
std::env::var("NIMA")
Out[27]:
Ok("1000")
In [28]:
std::env::remove_var("NIMA")
Out[28]:
()
In [25]:
let paths = std::env::var("PATH")?;
for path in std::env::split_paths(&paths) {
    println!("{:?}", path);
}
"/opt/pyenv/bin"
"/usr/local/sbin"
"/usr/local/bin"
"/usr/sbin"
"/usr/bin"
"/sbin"
"/bin"
"/usr/lib/jvm/java-8-openjdk-amd64/bin"
Out[25]:
()
In [12]:
std::env::join_paths(&["/workdir", "/home/dclong"])
Out[12]:
Ok("/workdir:/home/dclong")
In [29]:
std::env::temp_dir()
Out[29]:
"/tmp"

Comments