Running a Python script in the background from a PHP file - php

I need to run a Python script in the background after being called from a PHP file. The PHP file should continue to run independently of the Python script (i.e. it shouldn't hang waiting for the Python script to finish processing, but should instead carry on processing itself).
The Python script takes one argument and produces no output (it merely processes some data in the background), then exits. I'm running Python 2.6, PHP 5.2.6, and Ubuntu 9.04.

You could use exec() to kick off the Python interperator and have it send its output to either a file or to /dev/null with redirection. Using the & operator in the exec call will cause the command to be started and PHP to continue without waiting for a result.
http://www.developertutorials.com/tutorials/php/running-background-processes-in-php-349/ goes into more detail.

PHP Process Control can be used for this. The proc_open command can be used to start a process. You can later check up on it, read it's output etc.
View the manual entry: http://www.php.net/manual/en/function.proc-open.php and search around google for PHP Process Control

I'm guessing the PHP file is called via Apache, in which case you won't be able to fork(). You should make your Python script daemonize. Check out python-daemon.

You could use:
<?php
shell_exec('./test.sh &');
?>
where ./test.sh should be the execution line to your script

Related

PHP runs Perl script from command line successfully but I get no output displayed

I have a problem displaying the results of a Perl script that I am calling from my PHP webpage. The Perl script constantly monitors a socket and will display the output of this when run from the command line and also saves the output to a file. I know the Perl script is being called and running successfully as the text file is being updated but I do not get the output on the webpage as I was hoping for.
I have tried using the system(), exec(), passthru() and they all allow the Perl script to run but still with no output on the webpage so I am obviously missing something. Am I using the correct functions? Is there a parameter that I need to add to one of the above to push the output back to the webpage that calls the Perl script?
One example of what I have tried from the PHP manual pages:
<?php
exec('perl sql.pl', $output, $retval);
echo "Returned with status $retval and output:\n";
print_r($output);
?>
Edited to include output example as text instead of image as requested.
# perl sql.pl
Connecting to the PBX 192.168.99.200 on port 1752
04/07 10:04:50 4788 4788 3256739 T912 200 2004788 A2003827 A
I'm no PHP expert, but I guess that exec waits for the external program to finish executing before populating the $output and $return variables and returning.
You say that your sql.pl program "constantly monitors a socket". That sounds like it doesn't actually exit until the user closes it (perhaps with a Ctrl-C or a Ctrl-Z). So, presumably, your PHP code sits there waiting for your Perl program to exit - but it never does.
So I think there are a few approaches I'd investigate.
Does sql.pl have a command-line option that tells it to run once and then quit?
Does PHP have a way to send a Ctrl-C or Ctrl-Z to sql.pl a second or so after you've started it?
Does PHP have a way to deal with external programs that never end? Can you open a pipe to the external process and read output from it a line at a time?

Stop a Python Script called in a PHP File when HTML page is exited

I have called a python script within my PHP page using the code below:
echo shell_exec("python object_detection_tutorial_cmsc265.py");
The python script generates image files in a loop until a certain condition is met. Example is the code below:
while (True):
cv2.imwrite('image' + str(loop) + '.png',image);
if (not condition):
break
When the HTML/PHP page is exited in the browser, I can see that the images are still increasing in number, that means the python is still executing. How will I stop the python script upon exiting PHP page?
Assuming your Python script is running in background, like this, you cannot.
If you want to handle this you will have to handle pid.
What following is kind of dirty, well using any kind of shell_exec is dirty anyway, but keep this in mind.
What you could do:
Make the Python script echo its pid at script startup
Use exec PHP function over shell_exec to get only script's first output line
Kill this pid before leaving your PHP script
Python
import os
print(os.getpid())
# your script
PHP
// code
$pid = intval(exec('python foo.py'))
exec("kill $pid")
Well, I'm not PHP developer, but google just told me it may be better to use posix_kill over exec("kill $pid").
Again, this is not clean code, it's hacky and depends a lot of the system.

Call Shell Command from PHP without considering output

I'm trying to write a cronjob which launches multiple processes that I want to run in parallel.
I'm using a foreach calling each command, but the command line waits for the output. I don't want it to put.
Was wondering if anyone ever used any library for this?
Add an ampersand after the command:
$ php task.php &
It will run that instance of php in the background and continue.
If you read the manual on passthru you'll notice it tells you how to avoid this...
If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.
So you can rely on UNIX fds to redirect output to something like /dev/null for example if you don't care about the output or to some file if you do want to save the output and this will avoid PHP waiting on the command to finish.
pssthru("somecommand > /some/path/to/file")

PHP run a non blocking system call

How can I run a non blocking system call in PHP?
The system call will call a streaming service run by a second PHP script.. So my page sits and waits on this call.
My two thoughts on a solution:
1: There exists a native method / parameter to execute a system call by non blocking
2: Run system() on a new C++ program that will then fork itself and run the actual php script, on a sep. thread
Is there a native method of executing system calls in a non blocking manner or do I need to hack around this...
I currently have shell_exec('nohup php /path/to/file.php &') but it still holds
From PHP manual:
If a program is started with this function, in order for it to
continue running in the background, the output of the program must be
redirected to a file or another output stream. Failing to do so will
cause PHP to hang until the execution of the program ends.
An example is provided in a comment on the same page (linux based):
If you want to start a php process that continues to run independently
from apache (with a different parent pid) use nohub. Example:
exec('nohup php process.php > process.out 2> process.err < /dev/null
&');

Initiating background process for running php file as background from another php page

I want initiate one php page as background process from another php page.
Use popen():
$command = 'php somefile.php';
pclose(popen($command,'r'));
This launches somefile.php as a background process.
This is a technique I used to get around restrictions applied by my webhost (who limited cronjobs to 15 minutes of execution time, so my backup scripts would always timeout).
exec( 'php somefile.php | /dev/null &' );
The breakdown of this line is:
exec() - PHP reference Runs the specified command, as if from the Linux Command Line.
php somefile.php: Invokes PHP to open, and run, somefile.php. This is the same behaviour as what would happen if that file was accessed through a web browser.
| ("pipe") - Sends the output of the proceeding command to a specified target. In this instance, it would "pipe" the content which would normally be read by the web browser accessing the file.
/dev/null - A blackhole. No, not kidding. It is a place where you send output if you just want it to disappear.
& - Appending this character to the end of a Linux command means "Do not wait - Send this to the background and continue."
So, in summary, the provided code will execute a PHP script, return no output, and not wait for it to finish before continuing onto the next line.
(And, as always, if any of these assumptions on my part are in error, I would love to be corrected by more knowledgeable members of the community.)
You have to make sure, that the background process is not terminated when the processing of the page finished. If you are on a Linux system, you could try to use the nohup command:
$command = 'nohup php somefile.php';
pclose(popen($command,'r'));
If it still gets terminated, you could try the "daemon" command.

Categories