简体   繁体   English

使用Symfony Process解析命令行输出

[英]Parse command line output using Symfony Process

Within my Symfony application I need to do several operation with files: list of files from a directory, decrypt them using gpg, parse the output with an external software and encrypt again. 在我的Symfony应用程序中,我需要对文件进行一些操作:目录中的文件列表,使用gpg对其解密,使用外部软件解析输出,然后再次加密。

My first question is: is this the right approach for this problem? 我的第一个问题是:这是解决此问题的正确方法吗? On another scenario, I'd have written bash/python scripts to do this, but since info (user ids, passphrases, etc) is read from a Symfony API I though it was quite convenient to embed the calls into the application. 在另一种情况下,我会编写bash / python脚本来执行此操作,但是由于从Symfony API中读取了信息(用户ID,口令等),因此将调用嵌入到应用程序中非常方便。

My second question is more specific: is there any way to efficiently handle the command line outputs and errors? 我的第二个问题更具体:是否有任何方法可以有效地处理命令行输出和错误? For instance, when I call 'ls' how can easily convert the output into an array of file names? 例如,当我调用“ ls”时,如何轻松地将输出转换为文件名数组?

private function decryptAction()
{
    $user_data_source = '/Users/myuser/datafiles/';

    // Scan directory and get a list of all files
    $process = new Process('ls ' . $user_data_source);

    try {
        $process->mustRun();
        $files = explode(' ', $process->getOutput());

        return $files;
    } catch (ProcessFailedException $e) {
        return $e->getMessage();
    }
}

Found the answer for my second question, but I am still very interested in your thoughts about the entire approach. 找到了第二个问题的答案,但我仍然对您对整个方法的想法非常感兴趣。

// Scan directory and get a list of all files
        $process = new Process('ls -1 ' . $user_data_source);

        try {
            $process->mustRun();
            $files = array_filter( explode("\n", $process->getOutput()), 'strlen');
            return $files;
        } catch (ProcessFailedException $e) {
            return $e->getMessage();
        }

Unless you really need an immediate response from the call, this kind of tasks are better left to a background process. 除非您真的需要呼叫立即响应,否则最好将此类任务留给后台流程。

So what I would do is write one or more Symfony commands that perform the described processes (read, decrypt, and so on). 因此,我要做的是编写一个或多个执行所描述过程(读取,解密等)的Symfony命令。

Those processes can be executed via crontab, or "daemonized" via another scheduler like Supervisord. 这些进程可以通过crontab执行,也可以通过其他调度程序(如Supervisord)“守护”。

Then, the API call only creates some kind of "semaphore" file that triggers the actual execution, or even better you can use some kind of queue system. 然后,API调用仅创建触发实际执行的某种“信号量”文件,甚至更好的是,您可以使用某种队列系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM