I try to run a Python script as a background process from PHP on Windows using exec()
on this way:
<?PHP
$python = 'C:\\Users\\User\\anaconda3\\python.exe';
$py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
$py_stdout = '> temp\\'.session_id()."_std.txt";
$py_stderror = '2> temp\\'.session_id()."_stde.txt";
exec("$py_bg $python $py_script $py_stdout $py_stderror &");
The script called and worked correctly, but PHP still waiting for the script.
I removed the end &
as I foundout it's only work on Linux and after searching other Q&A find this sulotion:
exec("start /B $py_bg $python $py_script $py_stdout $py_stderror");
But same result. How can I solve this problem?
=== UPDATE:
I used start /B
in the wrong way, I changed my code to this:
<?PHP
$python = 'C:\\Users\\User\\anaconda3\\python.exe';
$py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
$py_stdout = '> temp\\'.session_id()."_std.txt";
$py_stderror = '2> temp\\'.session_id()."_stde.txt";
$py_cmd = "$python $py_script $py_arg_1 $py_std $py_stde";
pclose(popen("start /B ". $py_cmd, "a"));
But now a Warning in PHP for popen()
:
Warning: popen(start /B ...,a): No error in C:\wamp\www\lab\start.php on line 50
and an other for pclose()
:
Warning: pclose() expects parameter 1 to be resource, bool given in ...
I checked PHP: popen - Manual and see there a
is not a valid mode, but I see this on several answers around here!
however:
The mode. Either 'r' for reading, or 'w' for writing.
By changing mode to r
, the script call and run in the background correctly and there is not an error or warning on PHP or Py.
<?PHP
$python = 'C:\\Users\\User\\anaconda3\\python.exe';
$py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
$py_stdout = '> temp\\'.session_id()."_std.txt";
$py_stderror = '2> temp\\'.session_id()."_stde.txt";
$py_cmd = "$python $py_script $py_arg_1 $py_std $py_stde";
pclose(popen("start /B ". $py_cmd, "r"));