Set - 6

Question 1 :

How do I send mail from a Python script?
Use the standard library module smtplib.

Answer :

Here's a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener. 

import sys, smtplib 
fromaddr = raw_input("From: ")
toaddrs = raw_input("To: ").split(',')
print "Enter message, end with ^D:"
msg = ''
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

A Unix-only alternative uses sendmail. The location of the sendmail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The sendmail manual page will help you out. Here's some sample code:

SENDMAIL = "/usr/sbin/sendmail" # sendmail location
import os
p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@example.com\n")
p.write("Subject: test\n")
p.write("\n") # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
print "Sendmail exit status", sts

 


Question 2 :

How do I avoid blocking in the connect() method of a socket?

Answer :

The select module is commonly used to help with asynchronous I/O on sockets.


Question 3 :

Are there any interfaces to database packages in Python? 

Answer :

Yes. 

Python 2.3 includes the bsddb package which provides an interface to the BerkeleyDB library. Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python.


Question 4 :

How do I generate random numbers in Python?

Answer :

The standard module random implements a random number generator. Usage is simple:

import random
random.random()

This returns a random floating point number in the range [0, 1).


Question 5 :

Can I create my own functions in C? 

Answer :

Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C.