0

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?

5
  • What exactly is your question here? Commented Feb 9, 2014 at 15:30
  • @Robert: I guess it is: "How do I properly start a Python script with an infinite loop using PHP?". Commented Feb 9, 2014 at 15:32
  • you want to stop your loop ? Commented Feb 9, 2014 at 15:33
  • Yes i want to start a Python script with an infinit loop. From PHP Commented Feb 9, 2014 at 15:34
  • Why you don't add & to let it run in the background? Commented Feb 9, 2014 at 15:36

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, the parameter '&' does not change anything. The PHP script continues in the endless loop.
Right, perhaps that's because the output should be redirected to /dev/null. So then it becomens 'shell_exec('sudo python /home/pi/blink.py 1 > /dev/null &')'. Does this work?
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>

Comments

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

1 Comment

I have tryed the command: exec('sudo python /home/pi/blink.py 1 &', $output, $return_var); but the Result is the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.