Movatterモバイル変換


[0]ホーム

URL:


Command

std::process

StructCommand 

1.0.0 ·Source
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

1.0.0 ·Source

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 forspawn orstatus, 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
usestd::process::Command;Command::new("sh")    .spawn()    .expect("sh command failed to start");
§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.

usestd::process::Command;Command::new("ls")    .arg("-l")// arg passed separately.spawn()    .expect("ls command failed to start");
1.0.0 ·Source

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:

.arg("-C /path/to/repo")

usage would be:

.arg("-C").arg("/path/to/repo")

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
usestd::process::Command;Command::new("ls")    .arg("-l")    .arg("-a")    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

pub fnargs<I, S>(&mut self, args: I) -> &mutCommand
where I:IntoIterator<Item = S>, S:AsRef<OsStr>,

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
usestd::process::Command;Command::new("ls")    .args(["-l","-a"])    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

pub fnenv<K, V>(&mut self, key: K, val: V) -> &mutCommand
where K:AsRef<OsStr>, V:AsRef<OsStr>,

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
usestd::process::Command;Command::new("ls")    .env("PATH","/bin")    .spawn()    .expect("ls command failed to start");
1.19.0 ·Source

pub fnenvs<I, K, V>(&mut self, vars: I) -> &mutCommand
where I:IntoIterator<Item =(K, V)>, K:AsRef<OsStr>, V:AsRef<OsStr>,

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 ·Source

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.

usestd::process::Command;Command::new("git")    .arg("commit")    .env_remove("GIT_DIR")    .spawn()?;
1.0.0 ·Source

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.

usestd::process::Command;Command::new("sort")    .arg("file.txt")    .env_clear()    .spawn()?;
1.0.0 ·Source

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
usestd::process::Command;Command::new("ls")    .current_dir("/bin")    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

pub fnstdin<T:Into<Stdio>>(&mut self, cfg: T) -> &mutCommand

Configuration for the child process’s standard input (stdin) handle.

Defaults toinherit when used withspawn orstatus, anddefaults topiped when used withoutput.

§Examples
usestd::process::{Command, Stdio};Command::new("ls")    .stdin(Stdio::null())    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

pub fnstdout<T:Into<Stdio>>(&mut self, cfg: T) -> &mutCommand

Configuration for the child process’s standard output (stdout) handle.

Defaults toinherit when used withspawn orstatus, anddefaults topiped when used withoutput.

§Examples
usestd::process::{Command, Stdio};Command::new("ls")    .stdout(Stdio::null())    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

pub fnstderr<T:Into<Stdio>>(&mut self, cfg: T) -> &mutCommand

Configuration for the child process’s standard error (stderr) handle.

Defaults toinherit when used withspawn orstatus, anddefaults topiped when used withoutput.

§Examples
usestd::process::{Command, Stdio};Command::new("ls")    .stderr(Stdio::null())    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

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
usestd::process::Command;Command::new("ls")    .spawn()    .expect("ls command failed to start");
1.0.0 ·Source

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 ·Source

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 ·Source

pub fnget_program(&self) -> &OsStr

Returns the path to the program that was given toCommand::new.

§Examples
usestd::process::Command;letcmd = Command::new("echo");assert_eq!(cmd.get_program(),"echo");
1.57.0 ·Source

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
usestd::ffi::OsStr;usestd::process::Command;letmutcmd = Command::new("echo");cmd.arg("first").arg("second");letargs: Vec<&OsStr> = cmd.get_args().collect();assert_eq!(args,&["first","second"]);
1.57.0 ·Source

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
usestd::ffi::OsStr;usestd::process::Command;letmutcmd = Command::new("ls");cmd.env("TERM","dumb").env_remove("TZ");letenvs: Vec<(&OsStr,Option<&OsStr>)> = cmd.get_envs().collect();assert_eq!(envs,&[    (OsStr::new("TERM"),Some(OsStr::new("dumb"))),    (OsStr::new("TZ"),None)]);
1.57.0 ·Source

pub fnget_current_dir(&self) ->Option<&Path>

Returns the working directory for the child process.

This returnsNone if the working directory will not be changed.

§Examples
usestd::path::Path;usestd::process::Command;letmutcmd = Command::new("ls");assert_eq!(cmd.get_current_dir(),None);cmd.current_dir("/bin");assert_eq!(cmd.get_current_dir(),Some(Path::new("/bin")));
Source

pub fnget_env_clear(&self) ->bool

🔬This is a nightly-only experimental API. (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
#![feature(command_resolved_envs)]usestd::process::Command;letmutcmd = Command::new("ls");assert_eq!(cmd.get_env_clear(),false);cmd.env_clear();assert_eq!(cmd.get_env_clear(),true);

Trait Implementations§

1.0.0 ·Source§

implCommandExt forCommand

Available onUnix only.
Source§

fnuid(&mut self, id:u32) -> &mutCommand

Sets the child process’s user ID. This translates to asetuid call in the child process. Failure in thesetuidcall will cause the spawn to fail.Read more
Source§

fngid(&mut self, id:u32) -> &mutCommand

Similar touid, but sets the group ID of the child process. This hasthe same semantics as theuid field.
Source§

fngroups(&mut self, groups: &[u32]) -> &mutCommand

🔬This is a nightly-only experimental API. (setgroups #90747)
Sets the supplementary group IDs for the calling process. Translates toasetgroups call in the child process.
Source§

unsafe fnpre_exec<F>(&mut self, f: F) -> &mutCommand
where F:FnMut() ->Result<()> +Send +Sync + 'static,

Schedules a closure to be run just before theexec function isinvoked.Read more
Source§

fnexec(&mut self) ->Error

Performs all the required setup by thisCommand, followed by callingtheexecvp syscall.Read more
Source§

fnarg0<S>(&mut self, arg: S) -> &mutCommand
where S:AsRef<OsStr>,

Set executable argumentRead more
Source§

fnprocess_group(&mut self, pgroup:i32) -> &mutCommand

Sets the process group ID (PGID) of the child process. Equivalent to asetpgid call in the child process, but may be more efficient.Read more
Source§

fnchroot<P:AsRef<Path>>(&mut self, dir: P) -> &mutCommand

🔬This is a nightly-only experimental API. (process_chroot #141298)
Set the root of the child process. This callschroot in the child process before executingthe command.Read more
Source§

fnsetsid(&mut self, setsid:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (process_setsid #105376)
1.15.0 ·Source§

unsafe fnbefore_exec<F>(&mut self, f: F) -> &mutCommand
where F:FnMut() ->Result<()> +Send +Sync + 'static,

👎Deprecated since 1.37.0: should be unsafe, usepre_exec instead
Schedules a closure to be run just before theexec function isinvoked.Read more
Source§

implCommandExt forCommand

Available onLinux only.
Source§

fncreate_pidfd(&mut self, val:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (linux_pidfd #82971)
Sets whether aPidFd should be created for theChildspawned by thisCommand.By default, no pidfd will be created.Read more
1.16.0 ·Source§

implCommandExt forCommand

Available onWindows only.
Source§

fncreation_flags(&mut self, flags:u32) -> &mutCommand

Sets theprocess creation flags to be passed toCreateProcess.Read more
Source§

fnshow_window(&mut self, cmd_show:u16) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_show_window #127544)
Sets the fieldwShowWindow ofSTARTUPINFO that is passed toCreateProcess.Allowed values are the ones listed inhttps://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
Source§

fnforce_quotes(&mut self, enabled:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_force_quotes #82227)
Forces all arguments to be wrapped in quote (") characters.Read more
Source§

fnraw_arg<S:AsRef<OsStr>>(&mut self, raw_text: S) -> &mutCommand

Append literal text to the command line without any quoting or escaping.Read more
Source§

fnasync_pipes(&mut self, always_async:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_async_pipes #98289)
Whenprocess::Command creates pipes, request that our side is always async.Read more
Source§

fnspawn_with_attributes( &mut self, attribute_list: &ProcThreadAttributeList<'_>,) ->Result<Child>

🔬This is a nightly-only experimental API. (windows_process_extensions_raw_attribute #114854)
Executes the command as a child process with the givenProcThreadAttributeList, returning a handle to it.Read more
Source§

fnstartupinfo_fullscreen(&mut self, enabled:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_startupinfo #141010)
When true, sets theSTARTF_RUNFULLSCREEN flag on theSTARTUPINFO struct before passing it toCreateProcess.
Source§

fnstartupinfo_untrusted_source(&mut self, enabled:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_startupinfo #141010)
When true, sets theSTARTF_UNTRUSTEDSOURCE flag on theSTARTUPINFO struct before passing it toCreateProcess.
Source§

fnstartupinfo_force_feedback(&mut self, enabled:Option<bool>) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_startupinfo #141010)
When specified, sets the following flags on theSTARTUPINFO struct before passing it toCreateProcess:Read more
Source§

fninherit_handles(&mut self, inherit_handles:bool) -> &mutCommand

🔬This is a nightly-only experimental API. (windows_process_extensions_inherit_handles #146407)
If this flag is set totrue, each inheritable handle in the callingprocess is inherited by the new process. If the flag isfalse, thehandles are not inherited.Read more
1.0.0 ·Source§

implDebug forCommand

Source§

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.

Auto Trait Implementations§

§

implFreeze forCommand

§

impl !RefUnwindSafe forCommand

§

implSend forCommand

§

implSync forCommand

§

implUnpin forCommand

§

impl !UnwindSafe forCommand

Blanket Implementations§

Source§

impl<T>Any for T
where T: 'static + ?Sized,

Source§

fntype_id(&self) ->TypeId

Gets theTypeId ofself.Read more
Source§

impl<T>Borrow<T> for T
where T: ?Sized,

Source§

fnborrow(&self) ->&T

Immutably borrows from an owned value.Read more
Source§

impl<T>BorrowMut<T> for T
where T: ?Sized,

Source§

fnborrow_mut(&mut self) ->&mut T

Mutably borrows from an owned value.Read more
Source§

impl<T>From<T> for T

Source§

fnfrom(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U>Into<U> for T
where U:From<T>,

Source§

fninto(self) -> U

CallsU::from(self).

That is, this conversion is whatever the implementation ofFrom<T> for U chooses to do.

Source§

impl<T, U>TryFrom<U> for T
where U:Into<T>,

Source§

typeError =Infallible

The type returned in the event of a conversion error.
Source§

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U>TryInto<U> for T
where U:TryFrom<T>,

Source§

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>

Performs the conversion.

[8]ページ先頭

©2009-2026 Movatter.jp