PHP -捕获和显示exec/shell_exec周期输出?

时间:2021-10-02 05:51:38

You can easily use exec() or shell_exec() to execute a system command, like ls -l /var/www/mysite and then output the result of the command.

您可以很容易地使用exec()或shell_exec()来执行系统命令,比如ls -l /var/www/mysite,然后输出命令的结果。

How would one execute and display the result of a command that periodically prints information out to the console?

如何执行并显示命令的结果,该命令定期将信息打印到控制台?

Example: You have a simply Python script. If you run the script from the console, it simply prints out some type of information to the console every 10 seconds forever until you force-quit the script.

示例:您有一个简单的Python脚本。如果您从控制台运行脚本,它只是每隔10秒向控制台打印一些类型的信息,直到您强制退出脚本为止。

How could use PHP to execute this python command and somehow capture and stream the output into the browser in realtime? Is something like this possible? I'm thinking there would have to be some sort of Ajax involved but I'm not sure.

如何使用PHP执行这个python命令,并以某种方式实时捕获并将输出流到浏览器中呢?这可能吗?我想一定会有某种Ajax的介入,但我不确定。

I tried doing something like this:

我试过这样做:

python myscript.py > output.txt

And then I was planning on maybe using Ajax to periodically tail or cat the content of the output.txt and display in the browser. But output.txt doesn't appear to have any content added to it until after the script has been force-quit.

然后我计划使用Ajax定期跟踪或跟踪输出内容。在浏览器中显示和显示。但输出。在脚本被强制退出之前,txt似乎没有添加任何内容。

1 个解决方案

#1


2  

You don't see any output to output.txt because it's being buffered. For python there's an option to make it line-buffered. From the manpage:

您没有看到任何输出输出。txt因为它被缓冲了。对于python,有一个选项可以使其行缓冲。从:

       -u     Force  the  binary I/O layers of stdin, stdout and stderr to be unbuffered.  The text I/O layer will still be
              line-buffered.

So your command would then become:

所以你的命令会变成:

python -u myscript.py > output.txt

For PHP the flush function should help you.

对于PHP,刷新函数应该会帮助您。

#1


2  

You don't see any output to output.txt because it's being buffered. For python there's an option to make it line-buffered. From the manpage:

您没有看到任何输出输出。txt因为它被缓冲了。对于python,有一个选项可以使其行缓冲。从:

       -u     Force  the  binary I/O layers of stdin, stdout and stderr to be unbuffered.  The text I/O layer will still be
              line-buffered.

So your command would then become:

所以你的命令会变成:

python -u myscript.py > output.txt

For PHP the flush function should help you.

对于PHP,刷新函数应该会帮助您。