Print a header in python - python

Is there a python equivalent to this in perl?
use CGI;
my $IN = new CGI;
print $IN->header();
# $IN->header(-type=>'image/gif');
I see that this will print a header along with the ENV information:
import cgi
cgi.test()
Obviously I don't need the ENV information when not debugging. Otherwise do I need to type the print "Content-type: text/html" or print "Content-type: image/gif" everytime or is there a module already written that is similar?

Related

Python script to check Namenode status

I am new to Python and currently only learned a few things by researching online. Just wanted to know why am i getting "error" as the output rather than "success". Please see code below:
#! /usr/bin/python -v
import os
import subprocess
f = os.popen("hdfs haadmin -getServiceState nn2")
now = f.read()
status = "active"
if now == status:
print "success"
else:
print 'error'
Thanks,
Anil
(moving comment to an answer)
Whenever pulling text from something like popen or anywhere, I like to use .strip() and usually .lower() to clean off the newlines and extra spaces.
#! /usr/bin/python -v
import os
import subprocess
f = os.popen("hdfs haadmin -getServiceState nn2")
now = f.read().lower().strip() # add strip here
if now == "active":
print "success"
else:
print 'error:', now # why not print out what it output?

How to switch users for Python CGI Programming?

I have an HTML form which is handled by a Python script using CGI programming. From my Python script, I want to switch users from apache2 to monkey. The reason is because I'm using os.system to run another script from within my Python script.
The Python script works fine but I keep getting Permission errors when executing this command: os.system('python other_script.py'). What I realize is that when I am running the HTML form, I am apache2 instead of monkey. I'd like to know how to switch users (as monkey not root) while executing the Python script.
Here is what my Python script looks like:
#!/usr/bin/python -W
# Import modules for CGI handling
import cgi, cgitb
import pwd
import grp
import sys
import os
# Create instance of FieldStorage
form = cgi.FieldStorage()
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '</body>'
print '</html>'
os.system('python other_script.py') # getting permission errors here

python cgi script is not executing in XAMPP

i am a beginner in python. I've installed python34, and xampp. I've changed the http.config file and added the .py extension in handler block. then i put my python script into xamp/bin-cgi and set the first line of the python script as, "#!C:/Python34/python.exe". But when i opens the file through localhost/cgi-bin/test.py it doesn't showing anything only a blank screen, Below the content of the file.
#!C:/Python34/python.exe
print "Content-type: text/html"
print
print "<html>"
print "<head>"
print "<title>welcome cgi</title>"
print "</head>"
print "<body>"
print "<h1>first python page</h1>"
print "<p>heihei</p>"
print "</body>"
print "</html>"
You should rewrite the first line like this:
#!"C:\Python34\python.exe"
You are using Python 2.7 with your print statements. That is the first error. YOu are calling the Python 3.4 interpreters.
Also, you need to change your first line to
#!/Python34/python
# -*- coding: UTF-8 -*-
# enable debugging
Then, change your print statements to have parentheses
print("Content-type: text/html")
print()
print("""<html>
<head>
<title>welcome cgi</title>
</head>
<body>
<h1>first python page</h1>
<p>heihei</p>
</body>
</html>""")
ATTENTION:
If you notice, I changed up your code a bit and got rid of a bunch of print statements. Instead, I used what's called a multiline string (instead of writing "blah" I would do """blah"""). For example if I did
print("asdasdasd
asdasdasdasdasd")
This wouldn't work
But, if I changed it to
print("""asdasdasdasdasd
asdasdasdasdasd""")
This would be a perfectly acceptable command. Every new line would be registered as a "\n" so really, the string we are printing out is "asdasdasdasdasd\nasdasdasdasdasd" where \n marks a new line

Send email in python using subprocess module

I wrote a script to retrieve weather report from a website and send it to my girfriend in the morning.
Using Gmail. Of course I can send it using my Postfix server. Here is the script.
What I'm not sure is how to use Popen() function in the situation with so many arguments.
I can send the mail using the command.
$ mail -s "おお様からの天気予報" abc#gmail.com < foo
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import urllib2
import subprocess
weather_url = "http://www.weather.com.cn/weather/101020100.shtml"
f=urllib2.urlopen(weather_url)
html = f.read()
soup = BeautifulSoup(html)
content = soup.title.string
with open("foo","w") as mail:
mail.write(content.encode('utf-8'))
command_line = 'mail -s "おお様からの天気予報" abc#gmail.com < foo'
li = command_line.split()
process = subprocess.Popen(li, shell=True)
returncode = process.wait()
The content of the weather report is in the foo file. Can somebody tell me how to use Popen() with so many arguments?
I tried a lot.
This script just doesn't seem to work.
You don't need to pass an argument list when you use shell=True you can just pass an argument string...
command_line = 'mail -s "おお様からの天気予報" abc#gmail.com < foo'
process = subprocess.Popen(command_line, shell=True)
Or.. you can not use the shell to interpret your arguments and pass a list...
command_line = 'mail -s "おお様からの天気予報" abc#gmail.com < foo'
li = command_line.split()
process = subprocess.Popen(li)
But you can't pass an argument list and use the shell to interpret it.
Based on the nature of your command, I would recommend passing a string to the shell to interpret. (the first option)

What does this Perl XML filter look like in Python?

curl -u $1:$2 --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if /<name>/; print "$2\n" if /<(title|name)>(.*)<\/\1>/;'
I have this shell script which gets the Atom feed with command-line arguments for the username and password. I was wondering if this type of thing was possible in Python, and if so, how I would go about doing it. The atom feed is just regular XML.
Python does not lend itself to compact one liners quite as well as Perl. This is primarily for three reasons:
With Perl, whitespace is insignificant in almost all cases. In Python, whitespace is very significant.
Perl has some helpful shortcuts for one liners, such as perl -ne or perl -pe that put an implicit loop around the line of code.
There is a large body a cargo-cult Perl one liners to do useful things.
That all said, this python is close to what you posted in Perl:
curl -u $1:$2 --silent "https://mail.google.com/mail/feed/atom" | python -c '
import sys
for s in sys.stdin:
s=s.strip()
if not s: print '\t',
else: print s
'
It is a little difficult to do better because, as stated in my comment, the Perl you posted is incomplete. You have:
perl -ne 'print "\t" if //; print "$2\n" if /(.*)/;'
Which is equivalent to:
LINE:
while (<>) {
print "\t" if //; # print a tab for a blank line
print "$2\n" if /(.*)/; # nonsensical. Print second group but only
# a single match group defined...
}
Edit
While it is trivial to rewrite that Perl in Python, here is something a bit better:
#!/usr/bin/python
from xml.dom.minidom import parseString
import sys
def get_XML_doc_stdin(f):
return xml.dom.minidom.parse(f)
def get_tagged_data2(tag, index=0):
xmlData = dom.getElementsByTagName(tag)[index].firstChild.data
return xmlData
data=sys.stdin.read()
dom = parseString(data)
ele2=get_tagged_data2('title')
print ele2
count=int(get_tagged_data2('fullcount'))
print count,"New Messages:"
for i in range(0,count):
nam=get_tagged_data2('name',i)
email=get_tagged_data2('email',i)
print " {0}: {1} <{2}>".format(i+1,nam,email)
Now save that in a text file, run chmod +x on it, then:
curl -u $1:$2 --silent "https://mail.google.com/mail/feed/atom" |
/path/pythonfile.py
It produces this:
Gmail - Inbox for xxxxxxx#gmail.com
2 New Messages:
1: bob smith <bob#smith.com>
2: Google Alerts <googlealerts-noreply#google.com>
edit 2
And if you don't like that, here is the Python 1 line filter:
curl -u $1:$2 --silent "https://mail.google.com/mail/feed/atom" |python -c '
import sys, re
for t,m in re.findall(r"<(title|name)>(.*)<\/\1>",sys.stdin.read()):
print "\t",m
'
You may use an "URL opener" from the urllib2 standard Python module with a handler for authentication. For example:
#!/usr/bin/env python
import getpass
import sys
import urllib2
def main(program, username=None, password=None, url=None):
# Get input if any argument is missing
username = username or raw_input('Username: ')
password = password or getpass.getpass('Password: ')
url = url or 'https://mail.google.com/mail/feed/atom'
# Create password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, url, username, password)
# Create HTTP Authentication handler and URL opener
authhandler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(authhandler)
# Fetch URL and print content
response = opener.open(url)
print response.read()
if __name__ == '__main__':
main(*sys.argv)
If you'd like to extract information from the feed too, you should check how to parse Password-Protected Feeds with feedparser.

Categories