#3.5. env:::環境變數、引數與目錄
std::env 模組為存取行程環境提供一致的進入點。命令列引數、環境變數和標準目錄路徑集中在同一處,並隱藏作業系統之間的差異。
#3.5.1. API
模組公開的函式與型別一覽。路徑參數遵循整個層級共用的引數慣例(Path 即 P: AsPath)。
// command-line arguments
fn args() -> List<str>; // [0] = program name; the runtime captures argc/argv at startup; non-UTF-8 bytes become U+FFFD
fn args_os() -> List<RawStr>; // non-UTF-8 preserved (rare)
// environment variables
fn var(name: str) throws (VarError) -> str;
fn var_os(name: str) -> RawStr | none;
fn vars() -> Vars; // implements Iterator<Item = (str, str)>; non-UTF-8 bytes become U+FFFD
fn vars_os() -> VarsOs; // implements Iterator<Item = (RawStr, RawStr)>
unsafe fn set_var(name: str, value: str) throws (IoError); // InvalidInput for a bad name or value (3.5.3)
unsafe fn remove_var(name: str) throws (IoError); // an unset name is not an error
// directories
fn current_dir() throws (IoError) -> Path; // InvalidData if the path is not UTF-8
fn set_current_dir(path: Path) throws (IoError);
fn home_dir() -> Path | none;
fn temp_dir() -> Path;
fn config_dir() -> Path | none; // macOS ~/Library/Application Support, otherwise $XDG_CONFIG_HOME / ~/.config
fn cache_dir() -> Path | none; // macOS ~/Library/Caches, otherwise $XDG_CACHE_HOME / ~/.cache
fn data_dir() -> Path | none; // macOS ~/Library/Application Support, otherwise $XDG_DATA_HOME / ~/.local/share
// splitting the PATH environment variable (OS-specific separator)
fn split_paths(paths: str) -> List<Path>; // ":" on unix, ";" on windows; empty pieces dropped; windows drops `"` quoting
fn join_paths<I: IntoIterator<Item = P>, P: AsPath>(paths: I) throws (JoinPathsError) -> str;
// the executable itself
fn current_exe() throws (IoError) -> Path; // InvalidData if the path is not UTF-8
// process ID
// the parent's id: os::unix::process::parent_id (3.10.5)
enum VarError {
NotPresent, // the variable does not exist
NotUnicode, // the value is not UTF-8 (read with var_os)
} // message(); + Display, Debug, Error, PartialEq, Eq, Clone, Copy
RawStr 是一個字串,原封不動地保存作業系統提供的位元組(可能不是 UTF-8)。當某個路徑含有分隔符(: / ;),或在 Windows 上含有 " 時,就會產生 JoinPathsError;其訊息會指出是哪個字元。
struct RawStr { /* OS bytes */ }
impl RawStr {
fn len(self) -> usize; // byte length
fn is_empty(self) -> bool;
fn to_str(self) throws (Utf8Error) -> str; // throws if not UTF-8
fn to_str_lossy(self) -> str; // ill-formed parts as U+FFFD
fn as_bytes(self) -> Slice<u8>; // a view, no copy
}
// RawStr: + Clone, PartialEq, Eq, Hash, Debug
struct JoinPathsError { .. } // private fields (0.5.10)
impl JoinPathsError {
fn path(self) -> str; // the path that cannot be joined
fn message(self) -> str;
}
在 Windows 上,這些位元組是作業系統的 UTF-16 以 WTF-8 表示;在該平台上:
impl RawStr {
fn from_wide(wide: Slice<u16>) -> RawStr;
fn as_wide(self) -> Slice<u16>; // a view of a list made for it
}
args、vars 和 RawStr::to_str_lossy 會把位元組中每個格式不正確的部分替換為 U+FFFD,每個最大的格式不正確子序列替換為一個,與 str::from_utf8_lossy 的做法相同(2.15.6);在 Windows 上,一個孤立的代理項是一個 U+FFFD。args_os、vars_os 和 var_os 保留原始位元組。
#3.5.2. 範例
這些 API 在實際程式中如何搭配運作。下面的範例一次展示命令列引數、環境變數和 PATH 搜尋的典型流程。
use std::{env, fs, process};
// CLI tool
let args = env::args();
if args.len() < 2 {
eprintln("usage: tool <input>");
process::exit(1);
}
let input = args[1];
process(input);
// environment variables
let log_level = (try? env::var("LOG_LEVEL")) ?? "info";
let home = env::home_dir() ?? panic("HOME not set");
let config = home / ".config" / "myapp.toml";
// PATH search
let path_str = try env::var("PATH");
for dir in env::split_paths(path_str) {
let candidate = dir / "myprog";
if fs::exists(candidate) {
log(f"found at {candidate:?}");
}
}
#3.5.3. set_var 與 remove_var 是 unsafe
set_var 和 remove_var 會改變整個行程的環境。行程之後啟動的子行程會繼承這個環境;若只要設定某一個子行程的環境,請使用 Command::env / env_remove(3.6),它們是安全的。
unsafe { try env::set_var("RUST_LOG", "debug"); } // first thing in main
let child = try Command::new("tool").env("LEVEL", "2").spawn(); // safe: this child only
兩者都是 unsafe fn。安全性要求:呼叫期間,除了透過 std::env 之外,不得有其他執行緒讀取或寫入環境。Nabi 自身的 var、var_os、vars、vars_os、set_var 和 remove_var 會取得同一把內部鎖,因此單純的 Nabi 程式碼之間不會發生競爭;但呼叫 getenv 或 setenv 的 C 程式碼(例如透過 FFI 使用的函式庫)不會取得這把鎖,與其競爭的 set_var 在 POSIX 平台上是未定義行為。在單執行緒程式中以及在 Windows 上,呼叫是健全的。建議的模式是在程式開始時、啟動執行緒之前呼叫 set_var。
兩者都會擲回 IoError。InvalidInput:名稱為空或含有 = 或 NUL,或值含有 NUL;這項檢查在每個目標上都相同,包括 Windows。其他任何失敗都是作業系統錯誤。移除未設定的變數不是錯誤。想要改為觸發 panic 的程式可以寫 try!。
#3.5.4. impl / target
各平台如何實作相同的語意:
| 項目 | linux/macos/windows | wasi |
|---|---|---|
args | argc/argv / GetCommandLine | wasi:cli |
var / vars | getenv / GetEnvironmentVariable | wasi:cli |
home_dir | $HOME / %USERPROFILE% | wasi(無此概念) |
temp_dir | $TMPDIR,否則 /tmp / %TMP%、%TEMP%、%USERPROFILE%、%SystemRoot% 中第一個已設定者,否則 C:\Windows(即 GetTempPath2W 的順序,直接讀取) | wasi |
config_dir | XDG / %APPDATA% | (無) |
current_dir | getcwd / GetCurrentDirectoryW | 若 $PWD 為絕對路徑且可到達則用它,否則為 /(WASI 沒有此概念;nabi run / nabi test 會傳入主機的目錄) |
current_exe | /proc/self/exe / _NSGetExecutablePath / GetModuleFileName | Unsupported(wasm32) |
標準路徑在 macOS 上使用 ~/Library/...,在其他 Unix 系統上使用 XDG Base Directory 規格($XDG_*_HOME 只在是絕對路徑時才採用;否則使用 ~/.config 等),在 Windows 上使用環境變數:home 用 %USERPROFILE%,config 與 data 用 %APPDATA%,cache 用 %LOCALAPPDATA%。當所讀取的變數($HOME 或對應的 Windows 變數)未設定或為空時,結果為 none。
發現錯誤? 在 GitHub 上編輯此頁 最後更新: