【发布时间】:2018-12-13 19:24:58
【问题描述】:
当点击按钮时,一个 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');
}?>
Python
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 问题? (=> 标签已移除,下次添加无关标签前请三思)。
-
也许你没有粘贴整个 Python 脚本,但如果你粘贴了,你错过了“sys”模块的导入。