PHP执行系统命令的有几个常用的函数

先附上测试用的python脚本

testCsv.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
import csv
import random
import sys

filepath = '/Users/magicyou/Desktop/python/temp/'
# 生成csv文件
def exportCsv(title,data):
    print('test')
    print('test2')
    time.sleep(10)
    fileName = time.strftime('%Y%m%d%H%M',time.localtime(time.time())) + '_'+ str(int(round((time.time()) * 1000))) + ".csv"
    with open(filepath + fileName,"w",newline='',encoding='gb18030') as csvfile: 
        writer = csv.writer(csvfile)
        # 先写入columns_name
        try:
            writer.writerow(title)
            writer.writerows(data)
        except:
            info = sys.exc_info() 
            return {'status':False, 'msg':'文件写入失败!'} 
    return {'status':True, 'fileName':hostName + fileName}

if __name__ == "__main__":
    import time
    title = ['序号','姓名','年龄','价值度','喜好']
    data = [['序号','姓名','年龄','价值度','喜好'],['序号','姓名','年龄','价值度','喜好'],['序号','姓名','年龄','价值度','喜好']]
    exportCsv(title,data)

1 system函数

说明

string system ( string $command [, int &$return_var ] )

同 C 版本的 system() 函数一样, 本函数执行 command 参数所指定的命令, 并且输出执行结果。
如果 PHP 运行在服务器模块中, system() 函数还会尝试在每行输出完毕之后, 自动刷新 web 服务器的输出缓存。

参数

参数 描述
command 要执行的命令。
return_var 如果提供 return_var 参数, 则外部命令执行后的返回状态将会被设置到此变量中。

返回值
成功则返回命令输出的最后一行, 失败则返回 FALSE

# 案例
$last_line = system('/usr/local/bin/python3 /Desktop/python/python/testCsv.py', $output);
print_r($last_line);
echo $output;

// 页面返回
// test
// test0

2 exec函数

说明

string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() 执行 command 参数所指定的命令

参数

参数 描述
command 要执行的命令。
output 如果提供了 output 参数, 那么会用命令执行的输出填充此数组, 每行输出填充数组中的一个元素。 数组中的数据不包含行尾的空白字符,例如 \n 字符。 请注意,如果数组中已经包含了部分元素,exec() 函数会在数组末尾追加内容。如果你不想在数组末尾进行追加, 请在传入 exec() 函数之前 对数组使用 unset() 函数进行重置
return_var 如果提供 return_var 参数, 则外部命令执行后的返回状态将会被设置到此变量中。

返回值
命令执行结果的最后一行内容。 如果你需要获取未经处理的全部输出数据, 请使用 passthru() 函数。
如果想要获取命令的输出内容, 请确保使用 output 参数。

# 案例
$last_line = exec('/usr/local/bin/python3 /Desktop/python/python/testCsv.py', $output,$status);
print_r($last_line);
var_dump($output);
echo $status;

# 页面返回
// test
// array(1) {
//   [0]=>
//   string(4) "test"
// }
// 0

3 popen函数

说明

resource popen ( string $command , string $mode )

打开一个指向进程的管道,该进程由派生给定的 command 命令执行而产生。

参数

参数 描述
command 要执行的命令。
mode 必需。规定连接模式。可能的值:r: 只读。w: 只写(打开并清空已有文件或创建一个新文件)

返回值
返回一个和 fopen() 所返回的相同的文件指针,只不过它是单向的(只能用于读或写)并且必须用 pclose() 来关闭。此指针可以用于 fgets(),fgetss() 和 fwrite()。 当模式为 'r',返回的文件指针等于命令的 STDOUT,当模式为 'w',返回的文件指针等于命令的 STDIN。
如果出错返回 FALSE。

# 案例
$handle = popen('/usr/local/bin/python3 /Desktop/python/python/testCsv.py', 'r');
print_r($handle);
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);

# 页面返回
// Resource id #2
// 'Resource id #2'; resource
// test

4 passthru函数

说明

void passthru ( string $command [, int &$return_var ] )

同 exec() 函数类似, passthru() 函数 也是用来执行外部命令(command)的。 当所执行的 Unix 命令输出二进制数据, 并且需要直接传送到浏览器的时候, 需要用此函数来替代 exec() 或 system() 函数。 常用来执行诸如 pbmplus 之类的可以直接输出图像流的命令。 通过设置 Content-type 为 image/gif, 然后调用 pbmplus 程序输出 gif 文件, 就可以从 PHP 脚本中直接输出图像到浏览器。

参数

参数 描述
command 要执行的命令。
return_var 如果提供 return_var 参数, Unix 命令的返回状态会被记录到此参数。

返回值
没有返回值。

# 案例
$returnVal = passthru('/usr/local/bin/python3 /Desktop/python/python/testCsv.py', $status);
print_r($status);
# 页面返回
// test
// 0

5 shell_exec函数

说明

string shell_exec ( string $cmd )

通过 shell 环境执行命令,并且将完整的输出以字符串的方式返回。

参数

参数 描述
command 要执行的命令。

返回值
命令执行的输出。 如果执行过程中发生错误或者进程不产生输出,则返回 NULL。
Note:
当进程执行过程中发生错误,或者进程不产生输出的情况下,都会返回 NULL, 所以,使用本函数无法通过返回值检测进程是否成功执行。 如果需要检查进程执行的退出码,请使用 exec() 函数。

# 案例
$returnVal = shell_exec('/usr/local/bin/python3 /Desktop/python/python/testCsv.py');
echo $returnVal;
# 页面返回
// test

Tip

上述案例都是php在等脚本执行完毕返回状态或者结果,怎样才能只调用脚本不等结果呢?
完整的命令如下:
这个命令好处是当程序报错,错误记录在log_testPython.txt

python3 /Desktop/python/python/testCsv.py > /temp/test/log_testPython.txt 2>&1 &

原理:该程序的输出被重定向到一个文件或者其它输出流去
你也可以这样:

当然,这样是不会获取到脚本报错信息的

python3 /Desktop/python/python/testCsv.py > /temp/test/null 2>&1 &
或者
python3 /Desktop/python/python/testCsv.py > /temp/test/null &

猜你喜欢

转载自blog.51cto.com/13943634/2165559