执行命令<br>
命令带参数时参数可作为其中一个参数，也可以将命令和参数组合为一个字符串传入

@param envp 环境变量参数，传入形式为key=value，null表示继承系统环境变量
@param dir 执行命令所在目录（用于相对路径命令执行），null表示使用当前进程执行的目录
@param cmds 命令
@return {@link Process}
@since 4.1.6
341690
public static Process exec(String[] envp, File dir, String... cmds) {
		if (ArrayUtil.isEmpty(cmds)) {
			throw new NullPointerException("Command is empty !");
		}

		// 单条命令的情况
		if (1 == cmds.length) {
			final String cmd = cmds[0];
			if (StrUtil.isBlank(cmd)) {
				throw new NullPointerException("Command is empty !");
			}
			cmds = StrUtil.splitToArray(cmd, StrUtil.C_SPACE);
		}
		try {
			return Runtime.getRuntime().exec(cmds, envp, dir);
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
643171
function(opt_exe) {
  /** @private {(string|undefined)} */
  this.exe_ = opt_exe;

  /** @private {!Array.<string>} */
  this.args_ = [];

  /** @private {!Object.<string, string>} */
  this.env_ = {};
  Object.keys(process.env).forEach(function(key) {
    this.env_[key] = process.env[key];
  }.bind(this));
  this.env_['MOZ_CRASHREPORTER_DISABLE'] = '1';
  this.env_['MOZ_NO_REMOTE'] = '1';
  this.env_['NO_EM_RESTART'] = '1';

  /** @private {promise.Promise.<!exec.Command>} */
  this.command_ = null;
}
734031
String getEnvVar( String key)
	{
		String envVal = System.getenv(key);

		return envVal != null ? envVal : "";
	}
671358
private static String readShellFromPasswdFile( String[] args )
    {
        Process process = null;
        BufferedReader reader = null;
        try
        {
            process = startProcess( args );
            reader = createReader( process );
            processPasswdFile( reader );
            process.waitFor();
            reader.close();
        }
        catch( InterruptedException t )
        {
            throw new EnvironmentException( t );
        }
        catch( IOException t )
        {
            throw new EnvironmentException( t );
        }
        finally
        {
            if( process != null )
            {
                process.destroy();
            }
            close( reader );
        }
        String message = "User " + USERNAME + " is not present in the passwd database";
        throw new EnvironmentException( message );
    }
844594
public static int execute(String command, String[] envVars, File dir, Receiver outputReceiver) throws IOException {
		return execute(getCommandArrayForCurrentOS(command), envVars, dir, outputReceiver);
	}
341612
protected int runCommand(final CCTask task, final File workingDir, final String[] cmdline) throws BuildException {
    return CUtil.runCommand(task, workingDir, cmdline, this.newEnvironment, this.env);
  }
1091585
public String runCommand(List<String> args)
      throws CloudSdkNotFoundException, IOException, ProcessHandlerException {
    sdk.validateCloudSdkLocation();

    StringBuilderProcessOutputLineListener stdOutListener =
        StringBuilderProcessOutputLineListener.newListener();
    StringBuilderProcessOutputLineListener stdErrListener =
        StringBuilderProcessOutputLineListener.newListenerWithNewlines();
    ExitCodeRecorderProcessExitListener exitListener = new ExitCodeRecorderProcessExitListener();

    // build and run the command
    List<String> command =
        new ImmutableList.Builder<String>()
            .add(sdk.getGCloudPath().toAbsolutePath().toString())
            .addAll(args)
            .build();

    Process process = new ProcessBuilder(command).start();
    LegacyProcessHandler.builder()
        .addStdOutLineListener(stdOutListener)
        .addStdErrLineListener(stdErrListener)
        .setExitListener(exitListener)
        .build()
        .handleProcess(process);

    if (exitListener.getMostRecentExitCode() != null
        && !exitListener.getMostRecentExitCode().equals(0)) {
      Logger.getLogger(Gcloud.class.getName()).severe(stdErrListener.toString());
      throw new ProcessHandlerException(
          "Process exited unsuccessfully with code " + exitListener.getMostRecentExitCode());
    }

    return stdOutListener.toString();
  }
432880
function envFileContent(cmdOptions) {
  var filePath, envFiles;
  var fileContent = '';
  if (cmdOptions.env) {
    envFiles = cmdOptions.env.split(',');
    for (var i = 0; i < envFiles.length; i++ ) {
      filePath = path.normalize(envFiles[i]);
      if (fs.existsSync(filePath)) {
	fileContent += fs.readFileSync(filePath, 'utf8');
	fileContent += "\n";
      }
    }
  } else if (fs.existsSync(parser.cmdWorkingDir(cmdOptions) + '/.env')) {
    filePath = parser.cmdWorkingDir(cmdOptions) + '/.env';
    fileContent = fs.readFileSync(filePath, 'utf8');
  }

  return fileContent;
}
976519
public Long startProcess(Long processId, String masterRequestId, String ownerType,
            Long ownerId, Map<String,String> vars, Map<String,String> headers) throws Exception {
        return startProcess(processId, masterRequestId, ownerType, ownerId, vars, null, null, headers);
    }
190629
def do(cmdline, runas=None, env=None):
    '''
    
    '''
    if not cmdline:
        # This is a positional argument so this should never happen, but this
        # will handle cases where someone explicitly passes a false value for
        # cmdline.
        raise SaltInvocationError('Command must be specified')

    path = _rbenv_path(runas)
    if not env:
        env = {}

    # NOTE: Env vars (and their values) need to be str type on both Python 2
    # and 3. The code below first normalizes all path components to unicode to
    # stitch them together, and then converts the result back to a str type.
    env[str('PATH')] = salt.utils.stringutils.to_str(   # future lint: disable=blacklisted-function
        os.pathsep.join((
            salt.utils.path.join(path, 'shims'),
            salt.utils.stringutils.to_unicode(os.environ['PATH'])
        ))
    )

    try:
        cmdline = salt.utils.args.shlex_split(cmdline)
    except AttributeError:
        cmdauth = salt.utils.args.shlex_split(six.text_type(cmdline))

    result = __salt__['cmd.run_all'](
        cmdline,
        runas=runas,
        env=env,
        python_shell=False
    )

    if result['retcode'] == 0:
        rehash(runas=runas)
        return result['stdout']
    else:
        return False
254211
function procEnvVar(cmdOptions, index) {
  var fileEnvVar = parser.parseEnvOpts(cmdOptions);
  // process.env holds references which can cause unwanted side effects
  // cloning prevents changes to the variable values
  var processEnvVar = _.clone(process.env);
  var envVar = _.extend(processEnvVar, fileEnvVar);
  envVar.PORT = (cmdOptions.port + index);
  return envVar;
}
530260
function main (processArgv, conf) {

  // CLI input
  var opts = getOpts(processArgv);
  var argv = opts.argv;

  // Update notifier
  if (!argv["no-notifier"]) {
    checkUpdate();
  }

  // Convert options "--help" and "-h" into command "help"
  if (argv.help) {
    processArgv = transformHelpArgs(processArgv);
    // Regenerate opts from newly forged process.argv
    opts = getOpts(processArgv);
    argv = opts.argv;
  }

  // "--version"
  if (argv.version) {
    showVersion();
  }

  var commandName = argv._[0];

  // Demand command name
  if (!commandName) {
    console.error("No command specified");
    opts.showHelp();
    process.exit(127);
  }

  // Load command module
  var command = commands.load(commandName);

  // Demand valid command
  if (!command) {
    console.error("Unknown command: " + commandName);
    opts.showHelp();
    process.exit(127);
  }

  process.on("exit", function () {
    ttys.stdin.end();
  });

  // Configure opts and run command (inside a domain to catch any error)
  commands.run(command, opts, conf).then(ok, fail);

  function ok () {
    process.exit(0);
  }

  function fail (e) {
    if (e.code === "EINTERRUPT") {
      process.exit(127);
    } else {
      console.error("%s", e);
      if (process.env.DEBUG) {
        throw e;
      }
      process.exit(1);
    }
  }
}
375482
private ProcessInfo executeProcess(boolean background,ProcessBuilder pb) 
	{
		try
		{
			
			 pb.directory(workingDirectory);
			 pb.redirectErrorStream(false);
			
			if(log != null)
				pb.redirectOutput(Redirect.appendTo(log));
			
			pb.environment().putAll(envMap);
			Process p = pb.start();

			String out = null;
			String error = null;
			
			if(background)
			{
				out = IO.readText(p.getInputStream(),true,defaultBackgroundReadSize);
				
				error = IO.readText(p.getErrorStream(),true,20);				
			}
			else
			{
				out = IO.readText(p.getInputStream(),true);
				
				error = IO.readText(p.getErrorStream(),true);	
				
			}
				
  	
			if(background)
				return new ProcessInfo(0, out, error);
			
			return new ProcessInfo(p.waitFor(),out,error);
		}
		catch (Exception e)
		{
			return new ProcessInfo(-1, null, Debugger.stackTrace(e));
		}
	}
756123
function runCommand(cmd, args, cb) {

	// set locale so we can be sure of consistency of command execution
	const env = extend(process.env, { LANG: 'en', LC_ALL: 'en', LC_MESSAGES: 'en' });

	const argArray = Array.isArray(args) ? args : args.split(' ');

	const s = spawn(cmd, argArray, {
		stdio: ['ignore', 'pipe', 'pipe'],
		env
	});

	let stdout = '';
	s.stdout.on('data', (data) => {
		stdout += data;
	});

	let stderr = '';
	s.stderr.on('data', (data) => {
		stderr += data;
	});

	s.on('error', (error) => {
		cb(error, null, stdout, stderr);
	});

	s.on('close', (code) => {
		cb(null, code, stdout, stderr);
	});
}
361299
function Command(command, options) {
  var previousPath;

  this.command = command;

  // We're on Windows if `process.platform` starts with "win", i.e. "win32".
  this.isWindows = (process.platform.lastIndexOf('win') === 0);

  // the cwd and environment of the command are the same as the main node
  // process by default.
  this.options = defaults(options || {}, {
    cwd: process.cwd(),
    env: process.env,
    verbosity: (options && options.silent) ? 1 : 2,
    usePowerShell: false
  });

  // include node_modules/.bin on the path when we execute the command.
  previousPath = this.options.env.PATH;
  this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin');
  this.options.env.PATH += path.delimiter;
  this.options.env.PATH += previousPath;
}
262075
def execute(self, cmd, cwd):
        
        self.output = ""
        env = os.environ.copy()
        env.update(self.env)
        if six.PY2:  # nocv
            # Ugly hack because python 2.7.
            if self._stdout == self.DEVNULL:
                self._stdout = open(os.devnull, 'w+b')
            if self._stderr == self.DEVNULL:
                self._stderr = open(os.devnull, 'w+b')
        proc = subprocess.Popen(
            cmd, stdout=self._stdout, stderr=self._stderr,
            bufsize=0, universal_newlines=True,
            cwd=cwd, env=env,
            close_fds=ON_POSIX
        )
        for line in self._unbuffered(proc):
            self.line_handler(line)
        return_code = proc.poll()
        if return_code:
            logger.error(self.output)
            raise subprocess.CalledProcessError(
                return_code, cmd, output=str(self.output)
            )
        return self.output
698724
public static String exec(final String[] cmds, final long timeout) {
        try {
            final Process process = new ProcessBuilder(cmds).redirectErrorStream(true).start();
            final StringWriter writer = new StringWriter();
            new Thread(() -> {
                try {
                    IOUtils.copy(process.getInputStream(), writer, "UTF-8");
                } catch (final Exception e) {
                    LOGGER.log(Level.ERROR, "Reads input stream failed: " + e.getMessage());
                }
            }).start();

            if (!process.waitFor(timeout, TimeUnit.MILLISECONDS)) {
                LOGGER.log(Level.WARN, "Executes commands [" + Arrays.toString(cmds) + "] timeout");
                process.destroy();
            }

            return writer.toString();
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "Executes commands [" + Arrays.toString(cmds) + "] failed", e);

            return null;
        }
    }