I want the process i initiate through the script to run on webserver even if user closes the page.
It doesn't seem to be working with this:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgi,cgitb,subprocess
print "Content-Type: text/plain;charset=utf-8"
print
form = cgi.FieldStorage()
ticker = form['ticker'].value
print subprocess.Popen(['/usr/bin/env/python','options.py',ticker])
Please help! Thanks!
I guess this is wrong:
'/usr/bin/env/python'
it should be usually:
'/usr/bin/env python'
but better use this:
>>> import sys
>>> sys.executable # contains the executable running this python process
'C:\\Python27\\pythonw.exe'
I use to do it like this:
p = subprocess.Popen([sys.executable,'options.py',ticker])
Related
I am trying to build a redirect service that will allow me to track clicks within emails I send to foreign websites.
Example of the URL of this script:
https://example.com/cgi-bin/redir.py?rurl=https%3A%2F%2Fwww.example.com%2Fde&utm_content=test
I am using Apache2 on Ubunut20.04 with the cgi module, calling the following redir.py script:
#!/usr/bin/python3
import webbrowser
redirect_url = "https://www.example.com"
webbrowser.open(redirect_url)
Now this results in the following error:
End of script output before headers: redir.py
Adding a header:
print('Content-Type: text/plain')
print('')
print('hello world')
With this "hello world" output I get exactly this, a "hello world" message.
How to redirect if a header is needed?
Everything you print gets returned to the requesting browser. Your python file should look like this:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
print("Content-Type: text/html\n\n")
print()
print("<meta http-equiv=\"refresh\" content=\"0; url=TARGETURL\" />")
I have my python script that executes an mp3 when the current time matches the time specified in a text file. However everything works well but I notice a lag and delay of around 18 seconds before mplayer plays the mp3 file.
Is there anyway of making my python script better in order to get rid of the 18 seconds lag and make the mp3 file play instantaneously?
Here is my python script:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# import libraries
import json
import urllib2
from bs4 import BeautifulSoup
import requests
import datetime
import playsound
import os
import subprocess
dateSTR = datetime.datetime.now().strftime('%H:%M')
f = open('/home/pi/test.txt','r')
messagetest = f.read()
newnametest = messagetest.replace("\n","")
f.close()
if (dateSTR) == (newnametest):
os.system("mplayer -ao alsa:device=bluealsa /home/pi/test.mp3")
Try starting mplayer in a subprocess before you actually need it as:
p = subprocess.Popen('mplayer -slave -idle -ao alsa:device=bluealsa', shell=True, stdin=subprocess.PIPE)
That should start up mplayer and have it waiting for when you need it. Then, when you want to play a file, do:
p.communicate(input=b'loadfile /home/pi/test.mp3\n')
I'd create a loop, something like:
from time import sleep
from datetime import datetime
...
done = []
while 1:
dateSTR = datetime.now().strftime('%H:%M')
if (dateSTR) == (newnametest) and not dateSTR in done:
done.append(dateSTR)
os.system("mplayer -ao alsa:device=bluealsa /home/pi/test.mp3")
sleep(1)
I created a litlle script but I already have an error, I don't know what causes this or how to fix it, it's on an ubuntu vps, the error is located on this site:
http://alfaxtronic.koding.io/python.py
This is the Script:
#!/usr/bin/python
import os
import platform
import cgitb
cgitb.enable()
print "Content-Type: text/html"
print
print "hi"
form = cgi.FieldStorage()
You missed an import. Add this to the import lines at the top:
import cgi
I'm really enjoying Bottle so far, but the fact that I have to CTRL+C out of the server and restart it every time I make a code change is a big hit on my productivity. I've thought about using Watchdog to keep track of files changing then restarting the server, but how can I do that when the bottle.run function is blocking.
Running the server from an external script that watches for file changes seems like a lot of work to set up. I'd think this was a universal issue for Bottle, CherryPy and etcetera developers.
Thanks for your solutions to the issue!
Check out from the tutorial a section entitled "Auto Reloading"
During development, you have to restart the server a lot to test your
recent changes. The auto reloader can do this for you. Every time you
edit a module file, the reloader restarts the server process and loads
the newest version of your code.
This gives the following example:
from bottle import run
run(reloader=True)
With
run(reloader=True)
there are situations where it does not reload like when the import is inside a def. To force a reload I used
subprocess.call(['touch', 'mainpgm.py'])
and it reloads fine in linux.
Use reloader=True in run(). Keep in mind that in windows this must be under if __name__ == "__main__": due to the way the multiprocessing module works.
from bottle import run
if __name__ == "__main__":
run(reloader=True)
These scripts should do what you are looking for.
AUTOLOAD.PY
import os
def cherche(dir):
FichList = [ f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
return FichList
def read_file(file):
f = open(file,"r")
R=f.read()
f.close()
return R
def load_html(dir="pages"):
FL = cherche(dir)
R={}
for f in FL:
if f.split('.')[1]=="html":
BUFF = read_file(dir+"/"+f)
R[f.split('.')[0]] = BUFF
return R
MAIN.PY
# -*- coding: utf-8 -*-
#Version 1.0 00:37
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import datetime
import ast
from bottle import route, run, template, get, post, request, response, static_file, redirect
#AUTOLOAD by LAGVIDILO
import autoload
pages = autoload.load_html()
BUFF = ""
for key,i in pages.iteritems():
BUFF=BUFF+"#get('/"+key+"')\n"
BUFF=BUFF+"def "+key+"():\n"
BUFF=BUFF+" return "+pages[key]+"\n"
print "=====\n",BUFF,"\n====="
exec(BUFF)
run(host='localhost', port=8000, reloader=True)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import cgi
import string
import feedparser
count = 0
print "Content-Type: text/html\n\n"
print """<PRE><B>WORK MAINTENANCE/B></PRE>"""
d = feedparser.parse("http://www.hep.hr/ods/rss/radovi.aspx?dp=zagreb")
for opis in d:
try:
print """<B>Place/Time:</B> %s<br>""" % d.entries[count].title
print """<B>Streets:</B> %s<br>""" % d.entries[count].description
print """<B>Published:</B> %s<br>""" % d.entries[count].date
print "<br>"
count+= 1
except:
pass
I have a problem with CGI and paython script. Under the terminal script runs just fine except "IndexError: list index out of range", and I put pass for that. But when I run script through CGI I only get WORK MAINTENANCE line and first line from d.entries[count].title repeated 9 times? So confusing...
Also how can I setup support in feedparser for Croation(balkan) letters; č,ć,š,ž,đ ?
# -- coding: utf-8 -- is not working and I m running Ubuntu server.
Thank you in advance for help.
Regards.
for opis in d:
try:
print """<B>Place/Time:</B> %s<br>""" % d.entries[count].title
You're not using 'opis' in your output.
Try something like this:
for entry in d.entries:
try:
print """<B>Place/Time:</B> %s<br>""" % entry.title
....
Oke had another problem, text that I manualy entered would show on CGI but RSS web pages wouldnt. So you need to encode before you write:
# -*- coding: utf-8 -*-
import sys, os, string
import cgi
import feedparser
import codecs
d = blablablabla
print "Content-Type: text/html; charset=utf-8\n\n"
print
for entry in d.entries:
print """%s""" % entry.title.encode('utf-8')