当前位置:网站首页>[mikehaertl/php-shellcommand]一个用于调用外部命令操作的库
[mikehaertl/php-shellcommand]一个用于调用外部命令操作的库
2022-08-02 03:24:00 【phpreturn】
它提供了一个简单地方法接口来调用操作外部命令,可以用来替换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,
),
));
支持更多的参数方法
支持我们调用外部命令书需要多少所有方法,比如获取输出,获取错误,获取退出代码等.
边栏推荐
猜你喜欢
随机推荐
STM32 map文件解析
Source Insight 使用教程(2)——常用功能
STM32 触发HardFault_Handler如何查找原因
简单黑马头条项目
The querystring module
easyswoole 使用redis执行geoRadiusByMember Count无效修复
稳定好用的短连接生成平台,支持API批量生成
SQL分类、DQL(数据查询语言)、以及相应SQL查询语句演示
display,visibility,opacity
uniapp | 使用npm update更新后编译报错问题
区间问题 : 今年暑假不AC
阿里云服务器如何使用admin账户登录
解决MySQL创建子视图并查看的时候,字符集报错问题
meime module
js的“类数组”及“类数组转数组”
微信小程序全局组件的定义
C语言 结构体定义方法
URL URL
相对路径和绝对路径
微信小程序云开发-证件照的实现