[英]How to redirect php while the shell_exec() command is running at background?
單擊該按鈕時,將調用一個PHP頁面,該頁面依次執行shell_exec()命令,該命令會觸發python腳本。 問題在於,python腳本將花費將近30分鍾的時間執行,並且瀏覽器將一直處於運行狀態,直到腳本真正完成為止。 那么,是否有辦法在shell_exec命令被觸發時返回而python腳本在后台啟動呢?
if(isset($_POST['fire_automation_now'])){
$cmd = "python schedule_php.py now";
shell_exec($cmd);
header('location:index.php');
}
現在,它不會重定向到index.php,直到計划運行30分鍾的python腳本結束。
目前,我只是在延遲300秒后創建一個文本文件,以模仿腳本中的等待。
HTML
<form action="fire_automation.php" method="POST">
<div class=" row">
<div class="col-md-6">
<button type="submit" name="fire_automation_now" class="btn btn-large btn-success">Run Now</button>
</div>
</div>
</form>
PHP
<?php
if(isset($_POST['fire_automation_now'])){
$cmd = "python schedule_php.py now";
shell_exec($cmd);
header('location:index.php');
}?>
蟒蛇
import time
def now():
time.sleep(300)
open("test.txt", "w")
def main(choice):
if choice == "now":
now()
if __name__ == '__main__':
main(sys.argv[1])
謝謝。
要一次性運行Python腳本,您可以像這樣在后台運行它:
shell_exec("python schedule_php.py now > /dev/null 2>/dev/null &");
或者,如果無法正常運行,請將該呼叫與nohup
合並。
您可以使用:
exec($cmd . " > /dev/null &");
在PHP中。 然后命令將在后台運行
您可以使用功能ignore_user_abort
:
當將PHP作為命令行腳本運行時,腳本的tty消失而腳本未終止,則腳本將在下次嘗試寫入任何內容時死亡,除非將value設置為TRUE。
注意:
在嘗試將信息發送到客戶端之前,PHP不會檢測到用戶已中止連接。 簡單地使用echo語句並不能保證信息已發送,請參見flush()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.