简体   繁体   中英

PHP execute python script

I want to turn an LED on and off through a website (index.php) which is located in "/var/www/html" the two scripts are located in "/var/www/html/wspace/Server/" . Both scripts work perfectly fine when I execute them with ssh but I am not able to execute them through my php file.

In my index.php I wrote the following code for on-/off.py:

exec("/usr/bin/python3.5 /wspace/Server/on.py");

(I located the python installation with which python3.5 . The answer was /usr/bin/python3.5 .)

I have no idea what is wrong. Is it he command itself or do I have to change sth. in apache? What has to be changed that it works?

As further information the owner and permissions of the files:

index.php pi:pi 777
on.py pi:pi 777
off.py pi:pi 777

The apache user is likely "www-data" which doesn't, hopefully, have sudo access. Also multiple words in exec may act weird, I don't know. exec() may not even be executing bash so things like "&&" won't work.

Put

#!/usr/bin/python3

as the first line of the python script and

$chmod +x on.py

Then

exec("/var/www/html/wspace/Server/on.py")

Using relative pathing here isn't a good idea either because you don't know what the working directory is, though I'm sure can be specified.

If this still doesn't work then environment variables are the likely culprit, and you'll see something along the lines of "unknown environment: python3". I'm quoting from memory here so I may be off. If this is the case you'll have to call a bash script which exports PATH. You can log on to the box and echo $PATH as a regular user, don't matter for this case and then the bash script would be:

#!/bin/bash
export PATH=$PATH:<the stuff from 'echo $PATH'>
/var/www/html/wspace/Server/on.py

Don't forget to turn the executable bit on for this script either, chmod +x

Finally, your PHP would call the above bash script:

exec("<full path to bash script>")

It's important to realize that in all likely hood the argument passed to exec will not be run under the bash interpreter so the above may need to be done in a standalone script.

I had the same issue a while back.

For this scenario, you need to consider where the scripts are in relativity to the executing file. At the moment, you're preceding with a slash, so it's going to look from an absolute path from the root directory. If you remove this then it'll look relatively and should work.

Also, I found I had to include the whole path when executing python. Eg

exec('/usr/local/bin/python3 wspace/Server/on.py')

If this still doesn't work, try changing the directory and then executing the file:

exec('cd wspace/Server && /usr/local/bin/python3 on.py')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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