[mikehaertl/php-shellcommand]一个用于调用外部命令操作的库

2022-03-30 奥古斯宏

它提供了一个简单地方法接口来调用操作外部命令,可以用来替换exec.

相比直接调用exec,它具有以下几个特点:

  • 捕捉, stdOut,stdErr,exitCode
  • 处理复杂的参数
  • 支持环境变量和其他参数
  • 支持管道资源,比如文件或流
  • 可以超时执行

基本使用

<?php
use mikehaertl\shellcommand\Command;

// Basic example
$command = new Command('/usr/local/bin/mycommand -a -b');
if ($command->execute()) {
    echo $command->getOutput();
} else {
    echo $command->getError();
    $exitCode = $command->getExitCode();
}

高级使用

添加参数

<?php
$command = new Command('/bin/somecommand');
// Add arguments with correct escaping:
// results in --name='d'\''Artagnan'
$command->addArg('--name=', "d'Artagnan");

// Add argument with several values
// results in --keys key1 key2
$command->addArg('--keys', array('key1','key2'));

字符串输入

<?php
$command = new ('jq') // jq is a pretty printer
$command->setStdIn('{"foo": 0}');
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
// Output:
// {
//   "foo": 0
// }

把文件内容当做输入

<?php
$fh = fopen('test.json', 'r');
// error checks left out...
$command = new Command('jq');
$command->setStdIn($fh);
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
fclose($fh);

把URL内容当做输入

<?php
$fh = fopen('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relativehumidity_2m,windspeed_10m', 'r');
// error checks left out...
$command = new Command('jq');
$command->setStdIn($fh);
if (!$command->execute()) {
    echo $command->getError();
} else {
    echo $command->getOutput();
}
fclose($fh);

将命令封装好

<?php
// Create command with options array
$command = new Command(array(
    'command' => '/usr/local/bin/mycommand',

    // Will be passed as environment variables to the command
    'procEnv' => array(
        'DEMOVAR' => 'demovalue'
    ),

    // Will be passed as options to proc_open()
    'procOptions' => array(
        'bypass_shell' => true,
    ),
));

支持更多的参数方法

支持我们调用外部命令书需要多少所有方法,比如获取输出,获取错误,获取退出代码等.

最近浏览
IP用户:114.103.*.*
18 小时前 Internet Explorer Windows 7
IP用户:39.173.*.*
22 小时前 Generic Bot
IP用户:39.163.*.*
1 天前 Go-http-client
IP用户:54.36.*.*
2 天前 aHrefs Bot
IP用户:34.64.*.*
9 天前 Googlebot
IP用户:34.64.*.*
9 天前 Googlebot
IP用户:74.125.*.*
10 天前 Googlebot
IP用户:60.188.*.*
10 天前 Generic Bot
IP用户:34.64.*.*
11 天前 Googlebot
IP用户:54.36.*.*
12 天前 aHrefs Bot
IP用户:66.249.*.*
13 天前 Googlebot
IP用户:101.67.*.*
14 天前 Generic Bot
累计浏览次数:858
评论
点击登录
phpreturn,PHP武器库,专注PHP领域的项目和资讯,收录和介绍PHP相关项目。
最近浏览 点击登录
累计浏览次数:104676
一周浏览次数:2488
今日浏览次数:27

本站所有权利归 phpreturn.com 所有

举报/反馈/投稿邮箱:phpreturn@ulthon.com

鲁ICP备19027671号-2