Python tips and tricks

*This blog is moved to

**Below snippets, tips, trick and concepts actively collecting from various web sites and stack-overflow questions.

**You can find some examples snippets and useful tools at my repo

Operations on String

1.Check the string s is alphanumeric or not s.isalnum()

os & sys Module

1.Kill process from python (The script should run with sudo)

def kill(proc, signum=signal.SIGTERM):
    os.killpg(, signum)

2.Get pid of current script that is running:  os.getpid()

3.Give nice to the script that is running: os.nice(19)

4.Get the current python version: sys.version_info

5.Rename files: os.rename(src, dst)

6.Check file exists or not: os.path.exists("/path/to/file")

7.Get directory name of file: os.path.dirname(/path/to/file.txt)

8.Create directories recursively: os.makedirs("/dir1/dir2/")


1.Join list items with delimiter

>> days=["Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"]
>>> "-".join(days)


1.Print data and time. Find more at

  • %H– 24 Hours hour
  • %I– 12 Hours hour
  • %M– Minutes
  • %S-Seconds
  • %d– Days
  • %m– Months
  • %Y– Year [4 Digits]
  • %j– Day of the year
  • %A– Day of the week (Name)
>>> import time
>>> time.strftime("%H:%M:%S")
>>> time.strftime("%d/%m/%Y %H:%M:%S")
'14/03/2017 17:47:26'

2. Epoch time: int(time.time())

Reading and writing from/to different file formats

1.YAML Files


def read_yaml(file_name):
    if not os.path.exists(file_name):
        print "{} not found! Please check.".format(file_name)
    with open(file_name) as f:
    return data


def write_yaml(data,yaml_file):
    with, 'w', encoding='utf8') as outfile:
        yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True)


1. Know who is calling the function with inspect module (In-Built)

import inspect
def f1(): 
    print "Inside of function f1"    
def f2():
    curframe = inspect.currentframe()
    calframe = inspect.getouterframes(curframe, 2)
    print 'Caller Name:', calframe[1][3]

Inside of function f1
Caller Name: f1


2.Log rotate. (Include the below function in your script).


  1. message– Your information
  2. level– Log Level: debug, info, warning, error, critical
import logging
from logging.handlers import RotatingFileHandler

DEFAULT_LOG = '/var/log/script.log'
handler=RotatingFileHandler(DEFAULT_LOG, mode='a', maxBytes=20*1024*1024, backupCount=0, encoding=None, delay=0)
handler.setFormatter(logging.Formatter('%(asctime)s %(name)s[%(process)d] %(levelname)s: %(message)s'))
log =logging.getLogger('MyScript')

def log_it(level,message):
    if level=="info":       
    elif level=="debug":
    elif level=="warning":
    elif level=="error":
    elif level=="critical":

log_it("warning","Something happened!")

2017-03-14 12:19:53,391 MyScript[7602] WARNING: Something happened!;

3. Suppress all warnings in Python

import warnings

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s