dsf6778 2015-01-19 15:08
浏览 53

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

I'm trying to make a simple webpage which executes a seperate python script located in my home directory. There is nothing to be printed on the webpage since the script consists of commands to launch weather forecast and news reporting via the raspberry pi's speakers.

I searched high and low but could only find method to print system information on the page. If possible i wish to add a single button to the webpage (index.php) which when pressed will activate the script shown below. Thanks!

#!/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

21 January 2015:

Tried creating index.php with code

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

and runscript.php with

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

result: foo.txt was successfully created in /tmp folder.

However when I tried changing the command to sudo python /home/pi/alarm.py the script was not executed. I also tried changing index.php to

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

but webpage shows an internal server error when button(submit) was pressed.

  • 写回答

2条回答 默认 最新

  • duan117890 2015-01-19 15:17
    关注

    You just create a form (or even a link) that will point to a PHP page which exetues the script on the server.

    For the PHP part look at this piece of php manual about executing external programs and find out which best suits your needs. It may also depend on your platform/environment.

    For linux you could use something like

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

    You can omit the $output = thing if you don't need the textual output of the script.


    The complete package might look like this:

    the page with the link

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

    runscript.php

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

报告相同问题?