Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

May 6, 2014

Python 3 appindicator example script for Ubuntu 14.04

On Ubuntu 14.04 Python 3 is the default python version. Therefor If you try to run previous appindicator scripts on Ubuntu 14.04 those will not work. This script is done using Python 3 and relevant libraries.

Loading ....

Nov 13, 2011

Socket Programming with Python - Echo server

This is a basic socket program. You need to run the server first and then run the client.

Echo server (pechoserver.py)
#!/usr/bin/python

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("",5200)) # server is running on Port 5200
s.listen(1)

while 1:
 conn, addr = s.accept()
 print 'Connected IP ' , addr
 data = conn.recv(1024)
 if not data:
  break
 conn.send(data)
 conn.close()


Echo client (pechoclient.py)
#!/usr/bin/python

import socket
import sys

if (len(sys.argv)<1):
        print 'usage : pechoclient.py "message"'
        exit(0)
else:
        msg=sys.argv[1]
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect(("localhost",5200))
        s.send(msg)
        data=s.recv(1024)
        s.close()
        print "Recived : " ,data


Run the server ;
$ pyhton pechoserver.py &

Run the client ;
$ python pechoclient "Hello World."

Run client and server in different terminals to get a clear understanding of the output.

For more : http://docs.python.org/library/socket.html
                 http://docs.python.org/howto/sockets.html

Nov 10, 2011

Log your Python script - Python Logging Hello World

This is a basic logging script used in python.




#!/usr/bin/python

import sys
import logging

if (len(sys.argv)==2):
 loglevel=sys.argv[1]
else:
 loglevel="WARNING"

logging.basicConfig(filename='./mylogging.log',\
 format='%(levelname)s : %(asctime)s - %(message)s',\
 level=loglevel)
logging.debug('Logging started.')
logging.warning('Logging started.')

print "Hello World."
logging.debug("Print :- Hello World.")

logging.debug("End.")
logging.warning("End.")
exit(0)


Here I'm using a library called "logging" to do the logging for me. You can statically give the log level without passing it as an argument. And also there are many log levels you can use according to your need.

For more details :-  http://docs.python.org/library/logging.html

Your suggestions are welcome.