pub struct Command {/* private fields */ }Expand description
A process builder, providing fine-grained controlover how a new process should be spawned.
A default configuration can begenerated usingCommand::new(program), whereprogram gives a path to theprogram to be executed. Additional builder methods allow the configurationto be changed (for example, by adding arguments) prior to spawning:
usestd::process::Command;letoutput =ifcfg!(target_os ="windows") { Command::new("cmd") .args(["/C","echo hello"]) .output() .expect("failed to execute process")}else{ Command::new("sh") .arg("-c") .arg("echo hello") .output() .expect("failed to execute process")};lethello = output.stdout;Command can be reused to spawn multiple processes. The builder methodschange the command without needing to immediately spawn the process.
usestd::process::Command;letmutecho_hello = Command::new("sh");echo_hello.arg("-c").arg("echo hello");lethello_1 = echo_hello.output().expect("failed to execute process");lethello_2 = echo_hello.output().expect("failed to execute process");Similarly, you can call builder methods after spawning a process and thenspawn a new process with the modified settings.
usestd::process::Command;letmutlist_dir = Command::new("ls");// Execute `ls` in the current directory of the program.list_dir.status().expect("process failed to execute");println!();// Change `ls` to execute in the root directory.list_dir.current_dir("/");// And then execute `ls` again but in the root directory.list_dir.status().expect("process failed to execute");Implementations§
Source§implCommand
implCommand
1.0.0 ·Sourcepub fnnew<S:AsRef<OsStr>>(program: S) ->Command
pub fnnew<S:AsRef<OsStr>>(program: S) ->Command
Constructs a newCommand for launching the program atpathprogram, with the following default configuration:
- No arguments to the program
- Inherit the current process’s environment
- Inherit the current process’s working directory
- Inherit stdin/stdout/stderr for
spawnorstatus, but create pipes foroutput
Builder methods are provided to change these defaults andotherwise configure the process.
Ifprogram is not an absolute path, thePATH will be searched inan OS-defined way.
The search path to be used may be controlled by setting thePATH environment variable on the Command,but this has some implementation limitations on Windows(see issue #37519).
§Platform-specific behavior
Note on Windows: For executable files with the .exe extension,it can be omitted when specifying the program for this Command.However, if the file has a different extension,a filename including the extension needs to be provided,otherwise the file won’t be found.
§Examples
§Caveats
Command::new is only intended to accept the path of the program. If you pass a programpath along with arguments likeCommand::new("ls -l").spawn(), it will try to search forls -l literally. The arguments need to be passed separately, such as viaarg orargs.
1.0.0 ·Sourcepub fnarg<S:AsRef<OsStr>>(&mut self, arg: S) -> &mutCommand
pub fnarg<S:AsRef<OsStr>>(&mut self, arg: S) -> &mutCommand
Adds an argument to pass to the program.
Only one argument can be passed per use. So instead of:
usage would be:
To pass multiple arguments seeargs.
Note that the argument is not passed through a shell, but givenliterally to the program. This means that shell syntax like quotes,escaped characters, word splitting, glob patterns, variable substitution,etc. have no effect.
On Windows, use caution with untrusted inputs. Most applications use thestandard convention for decoding arguments passed to them. These are safe touse witharg. However, some applications such ascmd.exe and.bat filesuse a non-standard way of decoding arguments. They are therefore vulnerableto malicious input.
In the case ofcmd.exe this is especially important because a maliciousargument can potentially run arbitrary shell commands.
SeeWindows argument splitting for more detailsorraw_arg for manually implementing non-standard argument encoding.
§Examples
1.0.0 ·Sourcepub fnargs<I, S>(&mut self, args: I) -> &mutCommand
pub fnargs<I, S>(&mut self, args: I) -> &mutCommand
Adds multiple arguments to pass to the program.
To pass a single argument seearg.
Note that the arguments are not passed through a shell, but givenliterally to the program. This means that shell syntax like quotes,escaped characters, word splitting, glob patterns, variable substitution, etc.have no effect.
On Windows, use caution with untrusted inputs. Most applications use thestandard convention for decoding arguments passed to them. These are safe touse witharg. However, some applications such ascmd.exe and.bat filesuse a non-standard way of decoding arguments. They are therefore vulnerableto malicious input.
In the case ofcmd.exe this is especially important because a maliciousargument can potentially run arbitrary shell commands.
SeeWindows argument splitting for more detailsorraw_arg for manually implementing non-standard argument encoding.
§Examples
1.0.0 ·Sourcepub fnenv<K, V>(&mut self, key: K, val: V) -> &mutCommand
pub fnenv<K, V>(&mut self, key: K, val: V) -> &mutCommand
Inserts or updates an explicit environment variable mapping.
This method allows you to add an environment variable mapping to the spawned process oroverwrite a previously set value. You can useCommand::envs to set multiple environmentvariables simultaneously.
Child processes will inherit environment variables from their parent process by default.Environment variables explicitly set usingCommand::env take precedence over inheritedvariables. You can disable environment variable inheritance entirely usingCommand::env_clear or for a single key usingCommand::env_remove.
Note that environment variable names are case-insensitive (butcase-preserving) on Windows and case-sensitive on all other platforms.
§Examples
1.19.0 ·Sourcepub fnenvs<I, K, V>(&mut self, vars: I) -> &mutCommand
pub fnenvs<I, K, V>(&mut self, vars: I) -> &mutCommand
Inserts or updates multiple explicit environment variable mappings.
This method allows you to add multiple environment variable mappings to the spawned processor overwrite previously set values. You can useCommand::env to set a single environmentvariable.
Child processes will inherit environment variables from their parent process by default.Environment variables explicitly set usingCommand::envs take precedence over inheritedvariables. You can disable environment variable inheritance entirely usingCommand::env_clear or for a single key usingCommand::env_remove.
Note that environment variable names are case-insensitive (but case-preserving) on Windowsand case-sensitive on all other platforms.
§Examples
usestd::process::{Command, Stdio};usestd::env;usestd::collections::HashMap;letfiltered_env : HashMap<String, String> = env::vars().filter(|&(refk,_)| k =="TERM"|| k =="TZ"|| k =="LANG"|| k =="PATH").collect();Command::new("printenv") .stdin(Stdio::null()) .stdout(Stdio::inherit()) .env_clear() .envs(&filtered_env) .spawn() .expect("printenv failed to start");1.0.0 ·Sourcepub fnenv_remove<K:AsRef<OsStr>>(&mut self, key: K) -> &mutCommand
pub fnenv_remove<K:AsRef<OsStr>>(&mut self, key: K) -> &mutCommand
Removes an explicitly set environment variable and prevents inheriting it from a parentprocess.
This method will remove the explicit value of an environment variable set viaCommand::env orCommand::envs. In addition, it will prevent the spawned childprocess from inheriting that environment variable from its parent process.
After callingCommand::env_remove, the value associated with its key fromCommand::get_envs will beNone.
To clear all explicitly set environment variables and disable all environment variableinheritance, you can useCommand::env_clear.
§Examples
Prevent any inheritedGIT_DIR variable from changing the target of thegit command,while allowing all other variables, likeGIT_AUTHOR_NAME.
1.0.0 ·Sourcepub fnenv_clear(&mut self) -> &mutCommand
pub fnenv_clear(&mut self) -> &mutCommand
Clears all explicitly set environment variables and prevents inheriting any parent processenvironment variables.
This method will remove all explicitly added environment variables set viaCommand::envorCommand::envs. In addition, it will prevent the spawned child process from inheritingany environment variable from its parent process.
After callingCommand::env_clear, the iterator fromCommand::get_envs will beempty.
You can useCommand::env_remove to clear a single mapping.
§Examples
The behavior ofsort is affected byLANG andLC_* environment variables.Clearing the environment makessort‘s behavior independent of the parent processes’ language.
1.0.0 ·Sourcepub fncurrent_dir<P:AsRef<Path>>(&mut self, dir: P) -> &mutCommand
pub fncurrent_dir<P:AsRef<Path>>(&mut self, dir: P) -> &mutCommand
Sets the working directory for the child process.
§Platform-specific behavior
If the program path is relative (e.g.,"./script.sh"), it’s ambiguouswhether it should be interpreted relative to the parent’s workingdirectory or relative tocurrent_dir. The behavior in this case isplatform specific and unstable, and it’s recommended to usecanonicalize to get an absolute program path instead.
§Examples
1.0.0 ·Sourcepub fnspawn(&mut self) ->Result<Child>
pub fnspawn(&mut self) ->Result<Child>
Executes the command as a child process, returning a handle to it.
By default, stdin, stdout and stderr are inherited from the parent.
§Examples
1.0.0 ·Sourcepub fnoutput(&mut self) ->Result<Output>
pub fnoutput(&mut self) ->Result<Output>
Executes the command as a child process, waiting for it to finish andcollecting all of its output.
By default, stdout and stderr are captured (and used to provide theresulting output). Stdin is not inherited from the parent and anyattempt by the child process to read from the stdin stream will resultin the stream immediately closing.
§Examples
usestd::process::Command;usestd::io::{self, Write};letoutput = Command::new("/bin/cat") .arg("file.txt") .output()?;println!("status: {}", output.status);io::stdout().write_all(&output.stdout)?;io::stderr().write_all(&output.stderr)?;assert!(output.status.success());1.0.0 ·Sourcepub fnstatus(&mut self) ->Result<ExitStatus>
pub fnstatus(&mut self) ->Result<ExitStatus>
Executes a command as a child process, waiting for it to finish andcollecting its status.
By default, stdin, stdout and stderr are inherited from the parent.
§Examples
usestd::process::Command;letstatus = Command::new("/bin/cat") .arg("file.txt") .status() .expect("failed to execute process");println!("process finished with: {status}");assert!(status.success());1.57.0 ·Sourcepub fnget_program(&self) -> &OsStr
pub fnget_program(&self) -> &OsStr
Returns the path to the program that was given toCommand::new.
§Examples
1.57.0 ·Sourcepub fnget_args(&self) ->CommandArgs<'_>ⓘ
pub fnget_args(&self) ->CommandArgs<'_>ⓘ
Returns an iterator of the arguments that will be passed to the program.
This does not include the path to the program as the first argument;it only includes the arguments specified withCommand::arg andCommand::args.
§Examples
1.57.0 ·Sourcepub fnget_envs(&self) ->CommandEnvs<'_>ⓘ
pub fnget_envs(&self) ->CommandEnvs<'_>ⓘ
Returns an iterator of the environment variables explicitly set for the child process.
Environment variables explicitly set usingCommand::env,Command::envs, andCommand::env_remove can be retrieved with this method.
Note that this output does not include environment variables inherited from the parentprocess.
Each element is a tuple key/value pair(&OsStr, Option<&OsStr>). ANone valueindicates its key was explicitly removed viaCommand::env_remove. The associated key fortheNone value will no longer inherit from its parent process.
An empty iterator can indicate that no explicit mappings were added or thatCommand::env_clear was called. After callingCommand::env_clear, the child processwill not inherit any environment variables from its parent process.
§Examples
1.57.0 ·Sourcepub fnget_current_dir(&self) ->Option<&Path>
pub fnget_current_dir(&self) ->Option<&Path>
Sourcepub fnget_env_clear(&self) ->bool
🔬This is a nightly-only experimental API. (command_resolved_envs #149070)
pub fnget_env_clear(&self) ->bool
command_resolved_envs #149070)Returns whether the environment will be cleared for the child process.
This returnstrue ifCommand::env_clear was called, andfalse otherwise.Whentrue, the child process will not inherit any environment variables fromits parent process.
§Examples
Trait Implementations§
1.0.0 ·Source§implCommandExt forCommand
Available onUnix only.
implCommandExt forCommand
Source§fnuid(&mut self, id:u32) -> &mutCommand
fnuid(&mut self, id:u32) -> &mutCommand
setuid call in the child process. Failure in thesetuidcall will cause the spawn to fail.Read moreSource§fngid(&mut self, id:u32) -> &mutCommand
fngid(&mut self, id:u32) -> &mutCommand
uid, but sets the group ID of the child process. This hasthe same semantics as theuid field.Source§fngroups(&mut self, groups: &[u32]) -> &mutCommand
fngroups(&mut self, groups: &[u32]) -> &mutCommand
setgroups #90747)setgroups call in the child process.Source§unsafe fnpre_exec<F>(&mut self, f: F) -> &mutCommand
unsafe fnpre_exec<F>(&mut self, f: F) -> &mutCommand
exec function isinvoked.Read moreSource§fnprocess_group(&mut self, pgroup:i32) -> &mutCommand
fnprocess_group(&mut self, pgroup:i32) -> &mutCommand
setpgid call in the child process, but may be more efficient.Read moreSource§fnchroot<P:AsRef<Path>>(&mut self, dir: P) -> &mutCommand
fnchroot<P:AsRef<Path>>(&mut self, dir: P) -> &mutCommand
process_chroot #141298)chroot in the child process before executingthe command.Read moreSource§implCommandExt forCommand
Available onLinux only.
implCommandExt forCommand
1.16.0 ·Source§implCommandExt forCommand
Available onWindows only.
implCommandExt forCommand
Source§fncreation_flags(&mut self, flags:u32) -> &mutCommand
fncreation_flags(&mut self, flags:u32) -> &mutCommand
Source§fnshow_window(&mut self, cmd_show:u16) -> &mutCommand
fnshow_window(&mut self, cmd_show:u16) -> &mutCommand
windows_process_extensions_show_window #127544)wShowWindow ofSTARTUPINFO that is passed toCreateProcess.Allowed values are the ones listed inhttps://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindowSource§fnforce_quotes(&mut self, enabled:bool) -> &mutCommand
fnforce_quotes(&mut self, enabled:bool) -> &mutCommand
windows_process_extensions_force_quotes #82227)") characters.Read moreSource§fnraw_arg<S:AsRef<OsStr>>(&mut self, raw_text: S) -> &mutCommand
fnraw_arg<S:AsRef<OsStr>>(&mut self, raw_text: S) -> &mutCommand
Source§fnasync_pipes(&mut self, always_async:bool) -> &mutCommand
fnasync_pipes(&mut self, always_async:bool) -> &mutCommand
windows_process_extensions_async_pipes #98289)process::Command creates pipes, request that our side is always async.Read moreSource§fnspawn_with_attributes( &mut self, attribute_list: &ProcThreadAttributeList<'_>,) ->Result<Child>
fnspawn_with_attributes( &mut self, attribute_list: &ProcThreadAttributeList<'_>,) ->Result<Child>
windows_process_extensions_raw_attribute #114854)ProcThreadAttributeList, returning a handle to it.Read moreSource§fnstartupinfo_fullscreen(&mut self, enabled:bool) -> &mutCommand
fnstartupinfo_fullscreen(&mut self, enabled:bool) -> &mutCommand
windows_process_extensions_startupinfo #141010)STARTF_RUNFULLSCREEN flag on theSTARTUPINFO struct before passing it toCreateProcess.Source§fnstartupinfo_untrusted_source(&mut self, enabled:bool) -> &mutCommand
fnstartupinfo_untrusted_source(&mut self, enabled:bool) -> &mutCommand
windows_process_extensions_startupinfo #141010)STARTF_UNTRUSTEDSOURCE flag on theSTARTUPINFO struct before passing it toCreateProcess.Source§fnstartupinfo_force_feedback(&mut self, enabled:Option<bool>) -> &mutCommand
fnstartupinfo_force_feedback(&mut self, enabled:Option<bool>) -> &mutCommand
windows_process_extensions_startupinfo #141010)CreateProcess:Read moreSource§fninherit_handles(&mut self, inherit_handles:bool) -> &mutCommand
fninherit_handles(&mut self, inherit_handles:bool) -> &mutCommand
windows_process_extensions_inherit_handles #146407)true, each inheritable handle in the callingprocess is inherited by the new process. If the flag isfalse, thehandles are not inherited.Read more1.0.0 ·Source§implDebug forCommand
implDebug forCommand
Source§fnfmt(&self, f: &mutFormatter<'_>) ->Result
fnfmt(&self, f: &mutFormatter<'_>) ->Result
Format the program and arguments of a Command for display. Anynon-utf8 data is lossily converted using the utf8 replacementcharacter.
The default format approximates a shell invocation of the program along with itsarguments. It does not include most of the other command properties. The output is not guaranteed to work(e.g. due to lack of shell-escaping or differences in path resolution).On some platforms you can usethe alternate syntax to show more fields.
Note that the debug implementation is platform-specific.