doumenshi1475 2017-10-30 22:32
浏览 42

PHP执行python脚本

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
  • 写回答

2条回答 默认 最新

  • dsf45346 2017-10-30 22:46
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集