hexmode/io-mode

不仅仅是posix_isatty()

1.0 2019-06-23 22:46 UTC

This package is auto-updated.

Last update: 2024-08-25 09:12:16 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)