Skip to content
Advertisement

Capturing and displaying exec/shell_exec periodic output?

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.

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

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.

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.

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.

Advertisement

Answer

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:

       -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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement