#3.5. env:::环境变量 / args / 目录
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 调用的库)不会获取这把锁,在 POSIX 平台上,与它竞争的 set_var 是未定义行为。在单线程程序中以及在 Windows 上,调用是健全的。推荐的做法是在程序开始、启动线程之前调用 set_var。
两者都抛出 IoError。InvalidInput:名称为空或包含 = 或 NUL,或者值包含 NUL;这项检查在包括 Windows 在内的所有目标上都相同。其他失败是操作系统错误。删除未设置的变量不是错误。想要 panic 而不是错误的程序写 try!。
#3.5.4. 实现 / 目标
各平台实现同一语义的方式:
| 项 | 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 为绝对路径且可访问时取 $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 上使用环境变量:主目录用 %USERPROFILE%,config 和 data 用 %APPDATA%,cache 用 %LOCALAPPDATA%。所读取的变量($HOME 或 Windows 上对应的变量)未设置或为空时,结果为 none。
发现错误? 在 GitHub 上编辑此页 最后更新: