Struct otter_nodejs_tests::Command
1.0.0 · source · [−]pub struct Command { /* private fields */ }
Expand description
A process builder, providing fine-grained control over how a new process should be spawned.
A default configuration can be
generated using Command::new(program)
, where program
gives a path to the
program to be executed. Additional builder methods allow the configuration
to be changed (for example, by adding arguments) prior to spawning:
use std::process::Command;
let output = if cfg!(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")
};
let hello = output.stdout;
Command
can be reused to spawn multiple processes. The builder methods
change the command without needing to immediately spawn the process.
use std::process::Command;
let mut echo_hello = Command::new("sh");
echo_hello.arg("-c")
.arg("echo hello");
let hello_1 = echo_hello.output().expect("failed to execute process");
let hello_2 = echo_hello.output().expect("failed to execute process");
Similarly, you can call builder methods after spawning a process and then spawn a new process with the modified settings.
use std::process::Command;
let mut list_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
sourceimpl Command
impl Command
sourcepub fn new<S>(program: S) -> Command where
S: AsRef<OsStr>,
pub fn new<S>(program: S) -> Command where
S: AsRef<OsStr>,
Constructs a new Command
for launching the program at
path program
, 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
spawn
orstatus
, but create pipes foroutput
Builder methods are provided to change these defaults and otherwise configure the process.
If program
is not an absolute path, the PATH
will be searched in
an OS-defined way.
The search path to be used may be controlled by setting the
PATH
environment variable on the Command,
but this has some implementation limitations on Windows
(see issue #37519).
Examples
Basic usage:
use std::process::Command;
Command::new("sh")
.spawn()
.expect("sh command failed to start");
sourcepub fn arg<S>(&mut self, arg: S) -> &mut Command where
S: AsRef<OsStr>,
pub fn arg<S>(&mut self, arg: S) -> &mut Command where
S: AsRef<OsStr>,
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 see args
.
Note that the argument is not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, substitution, etc. have no effect.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.arg("-l")
.arg("-a")
.spawn()
.expect("ls command failed to start");
sourcepub fn args<I, S>(&mut self, args: I) -> &mut Command where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
pub fn args<I, S>(&mut self, args: I) -> &mut Command where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
Adds multiple arguments to pass to the program.
To pass a single argument see arg
.
Note that the arguments are not passed through a shell, but given literally to the program. This means that shell syntax like quotes, escaped characters, word splitting, glob patterns, substitution, etc. have no effect.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.args(["-l", "-a"])
.spawn()
.expect("ls command failed to start");
sourcepub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
Inserts or updates an environment variable mapping.
Note that environment variable names are case-insensitive (but case-preserving) on Windows, and case-sensitive on all other platforms.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.env("PATH", "/bin")
.spawn()
.expect("ls command failed to start");
1.19.0 · sourcepub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
Adds or updates multiple environment variable mappings.
Examples
Basic usage:
use std::process::{Command, Stdio};
use std::env;
use std::collections::HashMap;
let filtered_env : HashMap<String, String> =
env::vars().filter(|&(ref k, _)|
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");
sourcepub fn env_remove<K>(&mut self, key: K) -> &mut Command where
K: AsRef<OsStr>,
pub fn env_remove<K>(&mut self, key: K) -> &mut Command where
K: AsRef<OsStr>,
Removes an environment variable mapping.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.env_remove("PATH")
.spawn()
.expect("ls command failed to start");
sourcepub fn env_clear(&mut self) -> &mut Command
pub fn env_clear(&mut self) -> &mut Command
Clears the entire environment map for the child process.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.env_clear()
.spawn()
.expect("ls command failed to start");
sourcepub fn current_dir<P>(&mut self, dir: P) -> &mut Command where
P: AsRef<Path>,
pub fn current_dir<P>(&mut self, dir: P) -> &mut Command where
P: AsRef<Path>,
Sets the working directory for the child process.
Platform-specific behavior
If the program path is relative (e.g., "./script.sh"
), it’s ambiguous
whether it should be interpreted relative to the parent’s working
directory or relative to current_dir
. The behavior in this case is
platform specific and unstable, and it’s recommended to use
canonicalize
to get an absolute program path instead.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.current_dir("/bin")
.spawn()
.expect("ls command failed to start");
sourcepub fn stdin<T>(&mut self, cfg: T) -> &mut Command where
T: Into<Stdio>,
pub fn stdin<T>(&mut self, cfg: T) -> &mut Command where
T: Into<Stdio>,
Configuration for the child process’s standard input (stdin) handle.
Defaults to inherit
when used with spawn
or status
, and
defaults to piped
when used with output
.
Examples
Basic usage:
use std::process::{Command, Stdio};
Command::new("ls")
.stdin(Stdio::null())
.spawn()
.expect("ls command failed to start");
sourcepub fn stdout<T>(&mut self, cfg: T) -> &mut Command where
T: Into<Stdio>,
pub fn stdout<T>(&mut self, cfg: T) -> &mut Command where
T: Into<Stdio>,
Configuration for the child process’s standard output (stdout) handle.
Defaults to inherit
when used with spawn
or status
, and
defaults to piped
when used with output
.
Examples
Basic usage:
use std::process::{Command, Stdio};
Command::new("ls")
.stdout(Stdio::null())
.spawn()
.expect("ls command failed to start");
sourcepub fn stderr<T>(&mut self, cfg: T) -> &mut Command where
T: Into<Stdio>,
pub fn stderr<T>(&mut self, cfg: T) -> &mut Command where
T: Into<Stdio>,
Configuration for the child process’s standard error (stderr) handle.
Defaults to inherit
when used with spawn
or status
, and
defaults to piped
when used with output
.
Examples
Basic usage:
use std::process::{Command, Stdio};
Command::new("ls")
.stderr(Stdio::null())
.spawn()
.expect("ls command failed to start");
sourcepub fn spawn(&mut self) -> Result<Child, Error>
pub fn spawn(&mut self) -> Result<Child, Error>
Executes the command as a child process, returning a handle to it.
By default, stdin, stdout and stderr are inherited from the parent.
Examples
Basic usage:
use std::process::Command;
Command::new("ls")
.spawn()
.expect("ls command failed to start");
sourcepub fn output(&mut self) -> Result<Output, Error>
pub fn output(&mut self) -> Result<Output, Error>
Executes the command as a child process, waiting for it to finish and collecting all of its output.
By default, stdout and stderr are captured (and used to provide the resulting output). Stdin is not inherited from the parent and any attempt by the child process to read from the stdin stream will result in the stream immediately closing.
Examples
use std::process::Command;
use std::io::{self, Write};
let output = Command::new("/bin/cat")
.arg("file.txt")
.output()
.expect("failed to execute process");
println!("status: {}", output.status);
io::stdout().write_all(&output.stdout).unwrap();
io::stderr().write_all(&output.stderr).unwrap();
assert!(output.status.success());
sourcepub fn status(&mut self) -> Result<ExitStatus, Error>
pub fn status(&mut self) -> Result<ExitStatus, Error>
Executes a command as a child process, waiting for it to finish and collecting its status.
By default, stdin, stdout and stderr are inherited from the parent.
Examples
use std::process::Command;
let status = 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 fn get_program(&self) -> &OsStr
pub fn get_program(&self) -> &OsStr
Returns the path to the program that was given to Command::new
.
Examples
use std::process::Command;
let cmd = Command::new("echo");
assert_eq!(cmd.get_program(), "echo");
1.57.0 · sourcepub fn get_args(&self) -> CommandArgs<'_>ⓘNotable traits for CommandArgs<'a>impl<'a> Iterator for CommandArgs<'a> type Item = &'a OsStr;
pub fn get_args(&self) -> CommandArgs<'_>ⓘNotable traits for CommandArgs<'a>impl<'a> Iterator for CommandArgs<'a> type Item = &'a OsStr;
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 with Command::arg
and
Command::args
.
Examples
use std::ffi::OsStr;
use std::process::Command;
let mut cmd = Command::new("echo");
cmd.arg("first").arg("second");
let args: Vec<&OsStr> = cmd.get_args().collect();
assert_eq!(args, &["first", "second"]);
1.57.0 · sourcepub fn get_envs(&self) -> CommandEnvs<'_>ⓘNotable traits for CommandEnvs<'a>impl<'a> Iterator for CommandEnvs<'a> type Item = (&'a OsStr, Option<&'a OsStr>);
pub fn get_envs(&self) -> CommandEnvs<'_>ⓘNotable traits for CommandEnvs<'a>impl<'a> Iterator for CommandEnvs<'a> type Item = (&'a OsStr, Option<&'a OsStr>);
Returns an iterator of the environment variables that will be set when the process is spawned.
Each element is a tuple (&OsStr, Option<&OsStr>)
, where the first
value is the key, and the second is the value, which is None
if
the environment variable is to be explicitly removed.
This only includes environment variables explicitly set with
Command::env
, Command::envs
, and Command::env_remove
. It
does not include environment variables that will be inherited by the
child process.
Examples
use std::ffi::OsStr;
use std::process::Command;
let mut cmd = Command::new("ls");
cmd.env("TERM", "dumb").env_remove("TZ");
let envs: 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 · sourcepub fn get_current_dir(&self) -> Option<&Path>
pub fn get_current_dir(&self) -> Option<&Path>
Returns the working directory for the child process.
This returns None
if the working directory will not be changed.
Examples
use std::path::Path;
use std::process::Command;
let mut cmd = Command::new("ls");
assert_eq!(cmd.get_current_dir(), None);
cmd.current_dir("/bin");
assert_eq!(cmd.get_current_dir(), Some(Path::new("/bin")));
Trait Implementations
sourceimpl CommandExt for Command
impl CommandExt for Command
sourceimpl CommandExt for Command
impl CommandExt for Command
sourcefn uid(&mut self, id: u32) -> &mut Command
fn uid(&mut self, id: u32) -> &mut Command
Sets the child process’s user ID. This translates to a
setuid
call in the child process. Failure in the setuid
call will cause the spawn to fail. Read more
sourcefn gid(&mut self, id: u32) -> &mut Command
fn gid(&mut self, id: u32) -> &mut Command
Similar to uid
, but sets the group ID of the child process. This has
the same semantics as the uid
field. Read more
sourcefn groups(&mut self, groups: &[u32]) -> &mut Command
fn groups(&mut self, groups: &[u32]) -> &mut Command
setgroups
)Sets the supplementary group IDs for the calling process. Translates to
a setgroups
call in the child process. Read more
sourceunsafe fn pre_exec<F>(&mut self, f: F) -> &mut Command where
F: 'static + FnMut() -> Result<(), Error> + Send + Sync,
unsafe fn pre_exec<F>(&mut self, f: F) -> &mut Command where
F: 'static + FnMut() -> Result<(), Error> + Send + Sync,
Schedules a closure to be run just before the exec
function is
invoked. Read more
sourcefn exec(&mut self) -> Error
fn exec(&mut self) -> Error
Performs all the required setup by this Command
, followed by calling
the execvp
syscall. Read more
sourcefn arg0<S>(&mut self, arg: S) -> &mut Command where
S: AsRef<OsStr>,
fn arg0<S>(&mut self, arg: S) -> &mut Command where
S: AsRef<OsStr>,
Set executable argument Read more
sourcefn process_group(&mut self, pgroup: i32) -> &mut Command
fn process_group(&mut self, pgroup: i32) -> &mut Command
process_set_process_group
)Sets the process group ID of the child process. Translates to a setpgid
call in the child
process. Read more
Auto Trait Implementations
impl !RefUnwindSafe for Command
impl Send for Command
impl Sync for Command
impl Unpin for Command
impl !UnwindSafe for Command
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<T> Downcast for T where
T: Any,
impl<T> Downcast for T where
T: Any,
fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>ⓘNotable traits for Box<W, Global>impl<W> Write for Box<W, Global> where
W: Write + ?Sized, impl<R> Read for Box<R, Global> where
R: Read + ?Sized, impl<F, A> Future for Box<F, A> where
F: Future + Unpin + ?Sized,
A: Allocator + 'static, type Output = <F as Future>::Output;impl<I, A> Iterator for Box<I, A> where
I: Iterator + ?Sized,
A: Allocator, type Item = <I as Iterator>::Item;
fn into_any(self: Box<T, Global>) -> Box<dyn Any + 'static, Global>ⓘNotable traits for Box<W, Global>impl<W> Write for Box<W, Global> where
W: Write + ?Sized, impl<R> Read for Box<R, Global> where
R: Read + ?Sized, impl<F, A> Future for Box<F, A> where
F: Future + Unpin + ?Sized,
A: Allocator + 'static, type Output = <F as Future>::Output;impl<I, A> Iterator for Box<I, A> where
I: Iterator + ?Sized,
A: Allocator, type Item = <I as Iterator>::Item;
W: Write + ?Sized, impl<R> Read for Box<R, Global> where
R: Read + ?Sized, impl<F, A> Future for Box<F, A> where
F: Future + Unpin + ?Sized,
A: Allocator + 'static, type Output = <F as Future>::Output;impl<I, A> Iterator for Box<I, A> where
I: Iterator + ?Sized,
A: Allocator, type Item = <I as Iterator>::Item;
Convert Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
. Read more
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any + 'static>
Convert Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
. Read more
fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
Convert &Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s. Read more
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
Convert &mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s. Read more
impl<A> DynCastExt for A
impl<A> DynCastExt for A
fn dyn_cast<T>(
self
) -> Result<<A as DynCastExtHelper<T>>::Target, <A as DynCastExtHelper<T>>::Source> where
A: DynCastExtHelper<T>,
T: ?Sized,
fn dyn_cast<T>(
self
) -> Result<<A as DynCastExtHelper<T>>::Target, <A as DynCastExtHelper<T>>::Source> where
A: DynCastExtHelper<T>,
T: ?Sized,
Use this to cast from one trait object type to another. Read more
fn dyn_upcast<T>(self) -> <A as DynCastExtAdvHelper<T, T>>::Target where
A: DynCastExtAdvHelper<T, T, Source = <A as DynCastExtAdvHelper<T, T>>::Target>,
T: ?Sized,
fn dyn_upcast<T>(self) -> <A as DynCastExtAdvHelper<T, T>>::Target where
A: DynCastExtAdvHelper<T, T, Source = <A as DynCastExtAdvHelper<T, T>>::Target>,
T: ?Sized,
Use this to upcast a trait to one of its supertraits. Read more
fn dyn_cast_adv<F, T>(
self
) -> Result<<A as DynCastExtAdvHelper<F, T>>::Target, <A as DynCastExtAdvHelper<F, T>>::Source> where
A: DynCastExtAdvHelper<F, T>,
F: ?Sized,
T: ?Sized,
fn dyn_cast_adv<F, T>(
self
) -> Result<<A as DynCastExtAdvHelper<F, T>>::Target, <A as DynCastExtAdvHelper<F, T>>::Source> where
A: DynCastExtAdvHelper<F, T>,
F: ?Sized,
T: ?Sized,
fn dyn_cast_with_config<C>(
self
) -> Result<<A as DynCastExtAdvHelper<<C as DynCastConfig>::Source, <C as DynCastConfig>::Target>>::Target, <A as DynCastExtAdvHelper<<C as DynCastConfig>::Source, <C as DynCastConfig>::Target>>::Source> where
C: DynCastConfig,
A: DynCastExtAdvHelper<<C as DynCastConfig>::Source, <C as DynCastConfig>::Target>,
fn dyn_cast_with_config<C>(
self
) -> Result<<A as DynCastExtAdvHelper<<C as DynCastConfig>::Source, <C as DynCastConfig>::Target>>::Target, <A as DynCastExtAdvHelper<<C as DynCastConfig>::Source, <C as DynCastConfig>::Target>>::Source> where
C: DynCastConfig,
A: DynCastExtAdvHelper<<C as DynCastConfig>::Source, <C as DynCastConfig>::Target>,
Use this to cast from one trait object type to another. With this method the type parameter is a config type that uniquely specifies which cast should be preformed. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
fn instrument(self, span: Span) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
T: Future, type Output = <T as Future>::Output;
sourcefn in_current_span(self) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
fn in_current_span(self) -> Instrumented<Self>ⓘNotable traits for Instrumented<T>impl<T> Future for Instrumented<T> where
T: Future, type Output = <T as Future>::Output;
T: Future, type Output = <T as Future>::Output;
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
where
S: Into<Dispatch>,
T: Future, type Output = <T as Future>::Output;
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
fn with_current_subscriber(self) -> WithDispatch<Self>ⓘNotable traits for WithDispatch<T>impl<T> Future for WithDispatch<T> where
T: Future, type Output = <T as Future>::Output;
T: Future, type Output = <T as Future>::Output;
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more