能否将CLI命令(exec)的输出捕获到PHP脚本变量中?

问题描述 投票:0回答:1

我有一个外部库,里面有一堆可执行文件(DCMTK)。 通常,这些可执行文件可以在 CLI 上执行,输出有时会显示在终端中。 我想在PHP脚本中使用其中的一些,我能够用一个脚本做到这一点。

要点是。

// path to the executables.

private static $dcmtk_path = '/usr/local/opt/dcmtk/bin/';

//method to execute the dcmtk executable.

public static function dcmtk_command($command) {
    //--logfile dcmlogfile.cfg
    echo exec(self::$dcmtk_path . $command); // $outputarray, 2nd arg ?
    }
}

// working example that converts a text file to a dcm worklist file

file_put_contents (self::$MWL_PATH . "samplephp.txt", $template); // text file for MWL.
echo '[{"status":"Sent to PATH"}]';
self::dcmtk_command('dump2dcm ' . self::$MWL_PATH . "samplephp.txt " . self::$MWL_PATH . "samplephp.wl");

我不知道这是否可能。 但是,我是通过$_POST和get上传多个文件。

 $file_tmp = $files['tmp_name'];

那是保存在服务器上的一个路径。

 $success = move_uploaded_file($file_tmp, $upload_path);

然后我想执行另一个命令

self::dcmtk_command('dcmdump ' . $upload_path . $file_name );
// dcmdump +P StudyInstanceUID IM-0001-0004.dcm for specific tag

当从CLI执行时,会打印出一堆文本到终端(?STDOUT)。 我想做的是在PHP脚本中捕获该输出,以便我可以处理该输出。 我尝试了一些方法,比如使用输出缓冲区、exec命令中的$outputarray等。

似乎应该可以做到这一点。 文件以配置的路径保存在服务器上,所以它们应该在$upload_path . $file_name。 而且,我在PHP控制台的错误日志中没有看到任何错误。 实际上,我没有一个很好的方法来检查这个命令是否成功。

php stdout dcmtk
1个回答
0
投票

再次感谢。 这确实是个好办法。

$proc = proc_open($dcmtk_path . 'dcmdump +P StudyInstanceUID ' . $upload_path,[
1 => ['pipe','w'],
2 => ['pipe','w'],
],$pipes);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
proc_close($proc);
DatabaseFactory::logVariable( $stdout);  

如果我想的话,甚至可以只得到一个标签。 它捕获的单行在一个变量,如。

(0020,000d) UI [1.3.76.2.1.1.4.1.2.5310.511614778]      #  34, 1 StudyInstanceUID

需要一些函数来提取括号里的东西。

这几乎是可行的

$text = '(0020,000d) UI [1.3.76.2.1.1.4.1.2.5310.511614778]      #  34, 1 StudyInstanceUID';
preg_match_all("/\[([^\]]*)\]/", $text, $match);
print_r($match);

Array
(
    [0] => Array
        (
            [0] => [1.3.76.2.1.1.4.1.2.5310.511614778]
        )

    [1] => Array
        (
            [0] => 1.3.76.2.1.1.4.1.2.5310.511614778
        )

)

0
投票

作为后续,我希望有一种方法来捕获一个错误,如果这个过程出现了错误。 我强制执行了一个,它在输出流(不是错误流)中打印了这个。

作为后续,是否有可能捕捉到proc_open中的命令抛出的错误。 有一些情况下,可能会抛出错误。

例如,我在CLI上得到了看起来像警告和错误的东西(故意让它这样做)。 我希望有一种方法来捕获这些错误。

[07-May-2020 12:29:46 AmericaCayman]

W: DcmItem: Length of element (5089,474e) is odd
E: DcmElement: Unknown Tag & Data (5089,474e) larger (169478669) than remaining bytes in file
E: dcmdump: I/O suspension or premature end of stream: reading file: /Users/sscotti/Desktop/newtelerad2/dicomtemp/tattoo.dcm

看起来好像是

proc_get_status ( resource $process ) : array can give that with the exit code:

{
    "command": ". . . .",
    "pid": 8245,
    "running": false,
    "signaled": false,
    "stopped": false,
    **"exitcode": 1,**
    "termsig": 0,
    "stopsig": 0
}

谢谢你

© www.soinside.com 2019 - 2024. All rights reserved.