繁体   English   中英

当shell_exec()命令在后台运行时,如何重定向php?

[英]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.

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