当前位置:网站首页>[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,
),
));支持更多的参数方法
支持我们调用外部命令书需要多少所有方法,比如获取输出,获取错误,获取退出代码等.
边栏推荐
猜你喜欢
随机推荐
项目中遇到的问题
Common methods of js array deduplication
STM32 map文件解析
npm --package.json---require
由中序遍历和后序遍历得到前序遍历(树的遍历)
面试总结 22/7/22 面试中的重点
Living to detect the Adaptive Normalized Representation Learning for GeneralizableFace Anti - Spoofing reading notes
解决MySQL创建子视图并查看的时候,字符集报错问题
ES6三点运算符、数组方法、字符串扩展方法
这些JS题面试时一定要答对!
__dirname
---static page---
--fs module--
C语言 内联函数
解决 Zlibrary 卡死/找不到域名/达到限额问题,Zlibrary最新地址
暴力方法求解(leetcode14)查找字符串数组中的最大公共前缀
npm和package.json
三元判断再三元判断
Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
你的本地创建的项目库还在手动创建远端代码仓库再推送吗,该用它了









