Skip to content

mlawren/p5-Sys-Cmd

Repository files navigation

NAME
    Sys::Cmd - Run a system command or spawn a process

VERSION
    v0.0.0 (yyyy-mm-dd)

SYNOPSIS
        use Sys::Cmd qw/run runsub spawn/;

    Catch a command's standard output, warning on anything sent to
    stderr, raise an exception on abnormal exit:

        my $output = run( 'ls', '--long' );

    Commands can be fed input from Perl and return separate lines in in
    array context:

        my @XYZ = run( 'cat', '-n', { input => "X\nY\nZ\n", } );

    Put outputs and exit value directly into scalars, in which case no
    warnings or exceptions are triggered:

        my ($out, $err, $exit);
        run( 'ls', 'FILE_NOT_FOUND', {
            out => \$out,
            err => \$err,
            exit => \$exit,
        });

    A type of templating exists for multiple calls to the same command
    with pre-defined defaults:

        my $ls = runsub( 'ls',        # Returns a subref
            {
                dir => '/tmp',
                out => \$out,
            }
        );
        $ls->()                       &&  print $out;
        $ls->({ dir => '/elsewhere'}) &&  print $out;

    Use "spawn" for asynchronous interaction:

        my $proc = spawn( @cmd );
        printf "pid %d\n", $proc->pid;

        while ( defined ( my $line = $proc->stdout->getline ) ) {
            $proc->stdin->print("thanks\n");
        }
        warn $proc->stderr->getlines;

        $proc->wait_child || warn $proc->status;

DESCRIPTION
    Sys::Cmd lets you run a system command and capture its output, or
    spawn and interact with a process through its "stdin", "stdout" and
    "stderr" handles.

    It provides something of a superset of Perl's builtin external
    process functions ("system", "qx//", "fork"+"exec", and "open"):

    *   Command lookups using File::Which (run, spawn)

    *   Efficient process spawning with Proc::FastSpawn (run, spawn)

    *   Warn on error output (run)

    *   Raise exception on failure (run)

    *   Capture output, error and exit separately (run, spawn)

    *   Sensible exit and signal values

    *   Asynchronous interaction through file handles (spawn)

    *   Template functions for repeated calls (runsub, spawnsub)

  Command Path
    All functions take a @cmd list that specifies the command and its
    arguments. The first element of @cmd determines what/how things are
    run:

    *   If it has one or more path components (absolute or relative) it
        is executed as is, with Proc::FastSpawn.

    *   If it is a CODE reference (subroutine) then a fork is performed
        before calling it in the child process. Unsupported on Win32.

    *   Everything else is looked up using File::Which and the result is
        executed with Proc::FastSpawn.

    The remaining scalar elements of @cmd are passed as arguments.

  Common Options
    A function's @cmd list may also include an optional "\%opts" HASH
    reference to adjust aspects of the execution. The following
    configuration items (key => default) are common to all Sys::Cmd
    functions.

    dir => $CWD
        The working directory the command will be run in. Note that a
        relative command path might not be valid if the current
        directory changes.

    encoding => $Encode::Locale::ENCODING_LOCALE
        A string value identifying the encoding that applies to
        input/output file-handles, command arguments, and environment
        variables. Defaults to the 'locale' alias from Encode::Locale.

    env => {}
        A hashref containing key/values to be added to the current
        environment at run-time. If a key has an undefined value then
        the key is removed from the environment altogether.

    input => undef
        A scalar (string), or ARRAY reference, which is fed to the
        command via its standard input, which is then closed. An empty
        value ('') or empty list will close the command's standard input
        without printing. An undefined value (the default) leaves the
        handle open.

        Some commands close their standard input on startup, which
        causes a SIGPIPE when trying to write to it, for which Sys::Cmd
        will warn.

    on_exit
        A subref to be called at the time that process termination is
        detected.

FUNCTIONS
    The following functions are exportable from Sys::Cmd:

    run( @cmd, [\%opt] ) => $output | @output
        Executes @cmd and waits for the process to exit. Raises an
        exception in the event of non-zero exit value, otherwise warns
        for any errors received. In array context returns a list of
        lines instead of a scalar string. Accepts the following
        additional configuration keys:

        out => \$scalar
            A reference to a scalar which is populated with output. When
            given run() returns nothing.

        err => \$scalar
            A reference to a scalar which is populated with error
            output. When given run() does not warn of errors.

        exit => \$scalar
            A reference to a scalar which is populated with the exit
            value. When given run() does not raise an exception on a
            non-zero exit.

    spawn( @cmd, [\%opt] ) => Sys::Cmd::Process
        Return an object representing the process running according to
        @cmd and "\%opt". This is the core mechanism underlying "run".

        You can interact with the process object via its cmdline(),
        stdin(), stdout(), stderr(), close(), wait_child(), exit(),
        signal(), core() attributes and handles. See Sys::Cmd::Process
        for details.

  Template Functions
    When repeatedly calling a command, possibly with only slightly
    different arguments or environments, a kind of "templating"
    mechanism can be useful, to avoid repeating full configuration
    values and wearing a path lookup penalty each call.

    runsub( @cmd, [\%opt] ) => CODEref
        Returns a subroutine reference representing a *future* command
        to be executed in the style of "run", with default arguments and
        options. When called, additional arguments and options are
        *merged*:

            use Sys::Cmd 'runsub';
            my $git = runsub(
                'git',
                {
                    env => {
                        GIT_AUTHOR_NAME  => 'Geekette',
                        GIT_AUTHOR_EMAIL => '[email protected]',
                    }
                }
            );

            my @list   = $git->( 'add', 'file.txt' );
            my $result = $git->( 'commit', 'HEAD',
                {
                    env => {
                        GIT_AUTHOR_NAME  => 'Override',
                    }
                }
            ));

    spawnsub( @cmd, [\%opt] ) => CODEref
        Returns a subroutine reference representing a *future* process
        to be created in the style of "spawn", with default arguments
        and options. When called, additional arguments and options are
        *merged*.

            use Sys::Cmd 'spawnsub';
            my $cmd = spawnsub('command');
            my @kids;
            foreach my $i ( 0 .. 9 ) {
                $kids[$i] = $cmd->( 'arg', $i );
                $kids[$i]->stdin->print("Hello\n");
            }
            print $_->pid . ': ' . $_->stdout->getlines for @kids;
            $_->wait_child for @kids;

ALTERNATIVES
    AnyEvent::Run, AnyEvent::Util, Argv, Capture::Tiny, Child,
    Forks::Super, IO::Pipe, IPC::Capture, IPC::Cmd,
    IPC::Command::Multiplex, IPC::Exe, IPC::Open3, IPC::Open3::Simple,
    IPC::Run, IPC::Run3, IPC::RunSession::Simple, IPC::ShellCmd,
    IPC::System::Simple, POE::Pipe::TwoWay, Proc::Background,
    Proc::Fork, Proc::FastSpawn, Spawn::Safe, System::Command

SUPPORT
    This distribution is managed via github:

        https://github.com/mlawren/p5-Sys-Cmd

    This distribution follows the semantic versioning model:

        http://semver.org/

    Code is tidied up on Git commit using githook-perltidy:

        http://github.com/mlawren/githook-perltidy

AUTHOR
    Mark Lawrence <[email protected]>, based heavily on
    Git::Repository::Command by Philippe Bruhat (BooK).

COPYRIGHT AND LICENSE
    Copyright 2011-2025 Mark Lawrence <[email protected]>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

About

Perl Sys::Cmd module

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •