Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a python script through PHP and redirecting stdout, stderr to file

Tags:

shell

php

I have a PHP page that I want it to trigger a python script to run in the background and redirect its stdout and stderr to a file to be read later.

I tried the following:

system('python -u /home/omar/workspace/test/test2.py > /home/omar/workspace/test/testfile &');

This works fine in that the PHP doesn't block and the output is written to the file correctly.

But since this is only stdout, I tried putting &> instead of > :

system('python -u /home/omar/workspace/test/test2.py &> /home/omar/workspace/test/testfile &');

For some reason, this causes the page to block and the output of the python script is shown in the PHP page itself and nothing is written to the file!

Is there is a reason for this blasphemy?

like image 928
Omar Tarabai Avatar asked Feb 15 '26 07:02

Omar Tarabai


1 Answers

I solved it this way:

system('python -u test2.py > testfile 2>&1 & echo $!');

The last bit is to get the pid of the python instance.

like image 122
Omar Tarabai Avatar answered Feb 16 '26 21:02

Omar Tarabai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!