当前位置:网站首页>[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,
),
));支持更多的参数方法
支持我们调用外部命令书需要多少所有方法,比如获取输出,获取错误,获取退出代码等.
边栏推荐
- js 原型和原型链
- Common methods of js array deduplication
- 正则笔记(2)- 正则表达式位置匹配攻略
- [vite] Failed to parse source for import analysis because the content contains invalid JS syntax.
- Advanced gradient of skeleton effect, suitable for waiting for pictures
- 查询数据库中所有表的索引,并且解析成sql
- __dirname
- js scope and closure
- SQL:DDL、DML、DQL、DCL相应介绍以及演示
- Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG
猜你喜欢
随机推荐
每日五道面试题总结 22/7/20
1.8今日学习
---静态页面---
客户评分控件
querystring模块
我的小笔记 =》原生微信小程序
钟表刻度线
第一篇博客
require modular syntax
debian 10 nat and routing forwarding
Questions about your resume
由中序遍历和后序遍历得到前序遍历(树的遍历)
广州华为面试总结
STM32 触发HardFault_Handler如何查找原因
Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
--fs模块--
display,visibility,opacity
js预编译 GO 和AO
每日五道面试题总结 22/7/26
数组的高级操作









