PHP: exec command to get std errors

By appending 2>&1 at the end of the command will redirect errors from stderr to stdout.
Example:
If you run a simple command like cc at the command prompt, you would get the output as following
 $ cc  
 i686-apple-darwin10-gcc-4.2.1: no input files  
 $  
If u run the same command using PHP exec command
 $cmd = "cc";  
 exec($cmd,$out);  
 print_r($out);  
The output would be and empty array:
 Array ( )  
So, In order to get the error string as well, we need to append 2>&1
 $cmd = "cc 2>&1";  
 exec($cmd,$out);  
 print_r($out);  
The output will print:
 Array ( [0] => i686-apple-darwin10-gcc-4.2.1: no input files )  

2 comments:

  1. Thank you very much this really helped me, but why is it not redirecting out to the $out variable by default that one needs to use that?

    South Africa :)

    ReplyDelete
  2. Thank you for your comment Paul... One need to do it in order to redirect the error strings from stderr to stdout

    ReplyDelete

Python contextlib for Timing Python code

If you've ever found yourself needing to measure the execution time of specific portions of your Python code, the `contextlib` module o...