简体   繁体   中英

Send Parameter to a Python Script Running at Background From PHP

I have a python script (analyze.py) which takes a filename as a parameter and analyzes it. When it is done with analysis, it waits for another file name. What I want to do is:

  1. Send file name as a parameter from PHP to Python.
  2. Run analyze.py in the background as a daemon with the filename that came from PHP.

I can post the parameter from PHP as a command line argument to Python but I cannot send parameter to python script that already runs at the background.

Any ideas?

The obvious answer here is to either:

  1. Run analyze.py once per filename, instead of running it as a daemon.
  2. Pass analyze.py a whole slew of filenames at startup, instead of passing them one at a time.

But there may be a reason neither obvious answer will work in your case. If so, then you need some form of inter-process communication . There are a few alternatives:

  • Use the Python script's standard input to pass it data, by writing to it from the (PHP) parent process. (I'm not sure how to do this from PHP, or even if it's possible, but it's pretty simple from Python, sh, and many other languages, so …)
  • Open a TCP socket, Unix socket, named pipe, anonymous pipe, etc., giving one end to the Python child and keeping the other in the PHP parent. (Note that the first one is really just a special case of this one—under the covers, standard input is basically just an anonymous pipe between the child and parent.)
  • Open a region of shared memory, or an mmap -ed file, or similar in both parent and child. This probably also requires sharing a semaphore that you can use to build a condition or event, so the child has some way to wait on the next input.
  • Use some higher-level API that wraps up one of the above—eg, write the Python child as a simple HTTP service (or JSON-RPC or ZeroMQ or pretty much anything you can find good libraries for in both languages); have the PHP code start that service and make requests as a client.

Here is what I did.

PHP Part:

<?php

$param1 = "filename";

$command = "python analyze.py ";
$command .= " $param1";

$pid = popen( $command,"r");
 echo "<body><pre>";
while( !feof( $pid ) )
{
 echo fread($pid, 256);
 flush();
 ob_flush();
}
pclose($pid);

?>

Python Part:

1. I used [JSON-RPC]: https://github.com/gerold-penz/python-jsonrpc to
create a http service that wraps my python script (runs forever)
2. Created a http client that calls the method of http service.
3. Printed the results in json format.

Works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM