Run Python file from a PHP file


I would like you to help me with a problem that I have with my code, which I have been reviewing a lot but I can not fix it, this is my program in php, which runs on an Apache server (using raspberry pi 3 B), I will also leave you my python program, the objective of the program is to control the rotation of an engine, and its speed, but I can not execute the python file, but if I execute it from the command terminal, and I place the following:

cd /var/www/html
python 100 1 0 0

the led (first I'm testing it with a led) turns on, and if the number varies instead of 100, if it changes its intensity, but if I try to run from php, nothing happens physically with the led, even when I miss them if they print the corresponding values of 'x', 'y', 'z' and 'a'.


$instruccion=("python /var/www/html/ ".$x." ".$y." ".$z." ".$a);
/*tambien lo probe quitando el /var/www/html ya que se encuentran en la misma carpeta*/
echo $instruccion;      
echo $resultado;

'x' is the speed of the motor that the user inserts, 'der' is when the user presses the button that turns the motor to the right, 'left' the button on the left, and 'high' is the button to stop the engine. The echo $ instruction if it prints the value of $ instruction, and the echo $ result if it prints the values of 'x', and ',' z 'and' a '. here is my python program.

import RPi.GPIO as GPIO
import sys
GPIO.setup(12, GPIO.OUT)  
pwm = GPIO.PWM(12, 100)
GPIO.setup(11, GPIO.OUT) 
pwm2 = GPIO.PWM(11, 100)
vel= float(sys.argv[1])
p1= int(sys.argv[2])

while p3!=2:
 if p1==1:
 elif p2==1:


I think my problem is not so much in the python file, since it does run from the command line, rather in the php file, which is the one that does not run the python file. I want to clarify that the python file is 'executable', and has the permissions of the user www: data, just like the folder where the two files are located, I also want to clarify that both the php and python files are located together in the address / var / www / html

asked by esencia 30.09.2017 в 04:41

1 answer


Probably%% of PHP is not creating the full environment that the Python interpreter requires to run your program. Try using absolute paths to locate the interpreter:


Maybe you should even modify your Python program so that you can define the paths to the additional libraries that you include, since there is not a complete execution environment like when you run the program from your shell

On the other hand I suppose you are using Apache + PHP to generate your user interface with HTML and process the ways you capture the parameters. It's like using a tractor trailer with a double semitrailer to move a shoe box two meters away.

With a few modifications you can use the Python integrated web server from your own program to show your web interface, process the forms and execute the commands from a single, much lighter program. Your Raspberry PI will thank you

edit: Some improvements and suggestions to your code, also in this gist .

Later I will add the function that the integrated web server executes so that you avoid using apache and php

#!/usr/bin/env python
# −*− coding: UTF−8 −*−
# Las dos lineas anteriores se aseguran #1 de localizar el 
# interpretador para poder usar el script directamente
# y #2 de definir la codificacion de la fuente. Solo es
# buena educacion, =)

#import sys              # con argparse y la linea shebang! (#!) ya no lo ocupas
import argparse          # modulo utilisimo para lineas de comando
import RPi.GPIO as GPIO

def principal():
    ''' Secuencia principal a ejecutar cuando se llama desde
        la linea de comando en shell '''


    GPIO.setup(11, GPIO.OUT)
    GPIO.setup(12, GPIO.OUT)

    pwm = GPIO.PWM(12, 100) # (1): pwm asignado pero nunca usado
    pwm2 = GPIO.PWM(11, 100)

    pwm.start(0)            # (1): Tal vez hacia falta esto?

    #  vel = float(sys.argv[1])  # (6): Esto ya no es necesario,
    #  p1 = int(sys.argv[2])     # puedes hacer referencia al objeto
    #  p2 = int(sys.argv[3])     # args (linea 59) donde las propiedades
    #  p3 = int(sys.argv[4])     # corresponden a tus variables. argparse
                                 # ya se encargo de que sean del tipo correcto

    if args.verbose:

    while args.p3 != 2:
        if args.p1 == 1:                   # (2): Faltaba indentar tu bloque if para
            pwm.ChangeDutyCycle(args.vel)  # incluirlo en el bucle while
        elif args.p2 == 1:                 # (3): Revisa tu logica. la condicion
            pwm.ChangeDutyCycle(0)         # elif esta en una variable distinta al
            pwm2.ChangeDutyCycle(args.vel) # if original! seguro que asi debe ser?
    # (4): Este bucle if es infinito, el valor de p3 nunca cambiara!


if __name__ == '__main__':  # (5) Recurso idiomatico en python: de esta manera
                            # te aseguras que el programa se pueda ejecutar desde
                            # el shell, o que igual se pueda incluir como modulo
                            # en otro porgrama mas grande, mandando llamar al
                            # metodo principal()

    parser = argparse.ArgumentParser(description='Mi programa para controlar motores \
                                    con la Raspberry PI')
    parser.add_argument('vel', type=float, help='velocidad (punto flotante)')
    parser.add_argument('p1', type=int, help='velocidad (punto flotante)')
    parser.add_argument('p2', type=int, help='velocidad (punto flotante)')
    parser.add_argument('p3', type=int, help='velocidad (punto flotante)')
    parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
                        help='genera salida explicita (opcional)')

    args = parser.parse_args()

answered by 30.09.2017 в 09:55