hexmode/io-info

该包已被废弃,不再维护。作者建议使用 hexmode/io-mode 包。

不仅仅是posix_isatty()

1.0 2019-06-23 22:46 UTC

This package is auto-updated.

Last update: 2022-02-01 13:16:45 UTC


README

IOMode 基于StackOverflow上的一个 回答,并将该代码整合到一个可重用的库中。

来自 SO

我需要一个比posix_isatty更灵活的解决方案,可以检测

脚本是否在终端中运行?脚本是否通过管道或文件接收数据?输出是否被重定向到文件?

示例

此库可以使用以下方式使用

use Hexmode\IOMode;

if ( IOMode::isTTY() ) {
    print "tty\n";
}
if ( IOMode::isFifo() ) {
    print "pipe\n";
}
if ( IOMode::isReg() ) {
    print "regular file (redirection)\n";
}
if ( IOMode::isChr() ) {
    print "character device (normal)\n";
}
if ( IOMode::isDir() ) {
    print "directory (?!?!)\n";
}
if ( IOMode::isBlk() ) {
    print "block device\n";
}
if ( IOMode::isLnk() ) {
        print "symlink\n";
}
if ( IOMode::isSock() ) {
    print "socket\n";
}

(上面的脚本位于包含的 example/doc1.php。)

给定以下命令,您将得到不同的输出

$ php example/doc1.php
tty
character device (normal)
$ echo 1 | php example/doc1.php
pipe
$ mkdir tmp; php example/doc1.php < tmp;rmdir tmp
directory (?!?!)
$ sudo sh -c ‘php example/doc1.php> < /dev/sda1'
block device

与其他句柄一起使用

除了提供关于 STDIN 信息的 is*() 静态方法之外,还可以在 IOMode 对象上调用方法。

以下代码包含在 example/doc2.php

require( "vendor/autoload.php" );
use Hexmode\IOMode\IOMode;

$stderr = new IOMode( STDERR );
$stdout = new IOMode( STDOUT );
$stdin  = new IOMode( STDIN );

foreach (
	[ "in" => $stdin, "out" => $stdout, "err" => $stderr ] as $label => $io
) {
	if ( $io->TTY() ) {
		print "$label: tty\n";
	}
	if ( $io->Fifo() ) {
		print "$label: pipe\n";
	}
	if ( $io->Reg() ) {
		print "$label: regular file (redirection)\n";
	}
	if ( $io->Chr() ) {
		print "$label: character device (normal)\n";
	}
	if ( $io->Dir() ) {
		print "$label: directory (?!?!)\n";
	}
	if ( $io->Blk() ) {
		print "$label: block device\n";
	}
	if ( $io->Lnk() ) {
		print "$label: symlink\n";
	}
	if ( $io->Sock() ) {
		print "$label: socket\n";
	}
}

给定以下命令,您将得到不同的输出

$ sudo sh -c 'php example/doc2.php < /dev/nvme0n1p1'
in: block device
out: tty
out: character device (normal)
err: tty
err: character device (normal)
$ mkdir tmp; php example/doc2.php < tmp 2> /tmp/t;rmdir tmp
in: directory (?!?!)
out: tty
out: character device (normal)
err: regular file (redirection)
$ example/doc2.php > /tmp/t
$ cat /tmp/t; rm /tmp/t
in: tty
in: character device (normal)
out: regular file (redirection)
err: tty
err: character device (normal)