Calling a endless Python script from PHP

。_饼干妹妹 提交于 2020-03-05 06:18:02

问题


I have a PHP script that calls a python script. Both running on the same Linux server.

The Python script is running in a "while true" loop. Now when I start the PHP script, it remains in an endless loop and never ends.

If i delete the loop in Python, PHP is running normaly.

PHP:

<html>
 <head>
   <title>PHP</title>
 </head>
 <body>
  <?php 
      shell_exec('sudo python /home/pi/blink.py 1); 
  ?> 
 </body>
</html>

Python:

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import sys

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.cleanup()

GPIO.setup(4, GPIO.OUT)

def blink(self):
    while True:
        time.sleep(0.5);
        GPIO.output(4, GPIO.LOW)
        time.sleep(0.5);
        GPIO.output(4, GPIO.HIGH)

if  str(sys.argv[1]) is '1':
     blink("")
else:
     GPIO.output(4, GPIO.LOW)

Edit: How do I properly start a Python script with an infinite loop using PHP?


回答1:


Alright, one option is to include the Linux '&' in your shell_exec() function. This makes the command run in the background, you can't stop it (easily) from within the script though. Code then becomes (note the '&'):

<html>
 <head>
   <title>PHP</title>
 </head>
 <body>
  <?php 
      shell_exec('sudo python /home/pi/blink.py 1 &'); 
  ?> 
 </body>
</html>

This makes the script run in the background forever, or at least until the Pi is rebooted.




回答2:


Thanks to Robert Diepeveen

/dev/null &

This is the missing Piece

<html>
  <head>
    <title>PHP</title>
</head>
<body>
    <?php 
          shell_exec('sudo python /home/pi/blink.py 1 > /dev/null &');
    ?> 
</body>




回答3:


exec() — Execute an external program
for more details [php manual][1]


来源:https://stackoverflow.com/questions/21660993/calling-a-endless-python-script-from-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!