打开网页时在后台执行python脚本(不打印脚本)


Execute python script in the background when web page is opened (not printing a script)

我正在尝试制作一个简单的网页,该网页执行位于我的主目录中的单独python脚本。网页上没有打印任何内容,因为该脚本由通过树莓派的扬声器启动天气预报和新闻报道的命令组成。

我搜索了高低,但只能找到在页面上打印系统信息的方法。如果可能的话,我希望在网页上添加一个按钮(index.php),按下该按钮将激活如下所示的脚本。谢谢!

#!/bin/python
# -*- coding: utf-8 -*-
import ConfigParser
import subprocess
import time
import textwrap
import better_spoken_numbers as bsn
Config=ConfigParser.ConfigParser()
try:
  Config.read('alarm.config')
except:
  raise Exception('Sorry, Failed reading alarm.config file.')
wadparts=[]
for section in Config.sections():
  if section != 'main' and Config.get(section,'enabled')==str(1):
    try:
      wadparts.append(getattr(__import__('get_'+section, fromlist=[section]),section))
except ImportError:
  raise ImportError('Failed to load '+section)
count = 1
# key to getting text to speech
head = Config.get('main','head')+" "
tail = Config.get('main','tail')
day_of_month=str(bsn.d2w(int(time.strftime("%d"))))
now = time.strftime("%A %B ") + day_of_month + ',' + time.strftime(" %I %M %p")
# print now

if int(time.strftime("%H")) < 12:
  period = 'morning'
if int(time.strftime("%H")) >= 12:
  period = 'afternoon'
if int(time.strftime("%H")) >= 17:
  period = 'evening'
#print time.strftime("%H")
#print period
# reads out good morning + my name
gmt = 'Good ' + period + ', '
# reads date and time (sorry for the no apostrophe in it's)
day = ' its ' + now + '.  '
# Turn all of the parts into a single string
wad = (gmt + Config.get('main','name') + day + ''.join(str(x) for x in wadparts) + Config.get('main','end'))
if Config.get('main','debug') == str(1):
  print wad
if Config.get('main','readaloud') == str(1):
# strip any quotation marks
  wad = wad.replace('"', '').replace("'",'').strip()
  if Config.get('main','trygoogle') == str(1):
    # Google voice only accepts 100 characters or less, so split into chunks
    shorts = []
    for chunk in wad.split('.  '):
      shorts.extend(textwrap.wrap(chunk, 100))

    # Send shorts to Google and return mp3s
    try:
      for sentence in shorts:
        sendthis = sentence.join(['"http://translate.google.com/translate_tts?tl=en&q=', '" -O /mnt/ram/'])
        print(head + sendthis + str(count).zfill(2) + str(tail))
        print subprocess.check_output (head + sendthis + str(count).zfill(2) + str(tail), shell=True)
        count = count + 1
      # Play the mp3s returned
      print subprocess.call ('mpg123 -h 10 -d 11 /mnt/ram/*.mp3', shell=True)
    # festival is now called in case of error reaching Google
    except subprocess.CalledProcessError:
      print subprocess.check_output("echo " + wad + " | festival --tts ", shell=True)
    # Cleanup any mp3 files created in this directory.
    print 'cleaning up now'
    print subprocess.call ('rm /mnt/ram/*.mp3', shell=True)
  else:
    print subprocess.check_output("echo " + wad + " | festival --tts ", shell=True)
else:
  print wad

2015年1月21日:

尝试使用代码创建索引.php

<html>
<body>
    <a href="runscript.php">Run script.</a>
</body>
</html>

和运行脚本.php

<html>
<body>
    Starting script.
    <?php
        shell_exec('touch /tmp/foo.txt');
    ?>
</body>
</html>

结果:在/tmp 文件夹中成功创建了 FOO.txt。

但是,当我尝试将命令更改为sudo python/home/pi/alarm时.py脚本没有执行。我还尝试将索引.php更改为

<form action="alarm.py">
    <input type = "submit" value = "submit" name ="load">
</form>

但是网页在按下按钮(提交)时显示内部服务器错误。

index.php中添加以下代码

<form action="[your script name]">
    <input type = "submit" value = "submit" name ="load">
</form>

您只需创建一个表单(甚至链接),该表单将指向一个 PHP 页面,该页面在服务器上执行脚本。

对于PHP部分,请查看这本关于执行外部程序的php手册,并找出最适合您需求的方法。它还可能取决于您的平台/环境。

对于 linux,您可以使用类似的东西

$output = shell_exec('python /path/to/your/script.py');

如果您不需要脚本的文本输出,则可以省略$output =内容。


完整的包可能如下所示:

包含链接的页面

<html>
<body>
    <a href="runscript.php">Run script.</a>
</body>
</html>

运行脚本.php

<html>
<body>
    Starting script.
    <?php
        shell_exec('pyhton /path/to/your/script.py');
    ?>
</body>
</html>