I have spent a little time looking through the site, but ultimately wind up at the same place with code that stops functioning. I’m a coding novice and currently trying to learn HTML, PHP, python and SQL
I’m trying to trigger a python script from php code on a webserver. the python script and the webpage are located in the same folder on the server.
The website calls a script and is then supposed to open a new page to say the script ran.
The code I’m trying to call has a repeat function that runs every 10 seconds (this function is necessary) – this stops the webpage from loading.
This is the php.
if($datetime_diff < 2){
// code as ran within datetime diff value so all good - don't show button
echo "
<p>SQL Time check shows python code is running</p>
";
}else{
// show link to run python code
echo "
<p><a href='python_call.php' class='btn btn-primary ml-3'>Run python code</a></p>
";
}
this is the python call that is called in the href..
shell_exec('python pdl_test.py > error.txt 2>&1 &');
echo "
<p><a href='admin_page.php' class='btn btn-primary ml-3'>Admin Page</a></p>
";
I was under the impression that the 2>&1 & should allow the php to continue without checking for a result.
the error.txt file displays complete
this is the script that the first python code is calling..
def repeat():
print (datetime.now())
try:
subprocess.run(['python', 'sql_update.py'])
except:
print ('error')
else:
print ('called')
print (datetime.now())
print ("program complete")
time.sleep(10)
while True:
repeat()
and this is the SQL (this works OK)
cursorDestination.execute('''
UPDATE eng_pdl_test
SET scriptRan = getdate()
WHERE id = 1
''')
cnxnDestination.commit()
I can see from the Task manager program that the command is being executed, and is retained.
| Name | PID | Status | Command Line | |
|---|---|---|---|---|
| python.exe | 12476 | Running | python pdl_test.py |
If I close the first webpage and re-open it, the update shows as complete and, on page refresh the timer value increments every 10 seconds.
Also, if the pdl_test.py script is already running everything works correctly.
so ,in summary the code works correctly, it just doesn’t finish loading the page correctly.
Would someone please point me in a new/better/right direction please.
i’ve also tried Popen with no success.
subprocess.Popen(['python', 'sql_update.py'])
i’ve confirmed server calls are permitted using this code..
$output = null;
$return_var = null;
exec('echo "test"', $output, $return_var);
if ($return_var === 0) {
echo 'command execution permitted.';
} else {
echo 'command execution not permitted.';
}
if i call the sql_update.py script it works as expected. and I can return values if needed, but I can’t do this because I need the 10 second repeat.
exec('python sql_update.py', $output, $return_var);
echo "Output: " . implode("n", $output) . "n";
echo "Return value: " . $return_var . "n";