Python template script

Sat. November 12, 2011
Categories: bash, Linux, Python
Tags: , , ,

When creating a python script, one would usually have to do the following:


[ 14:35 jon@hozbox.com ~ ]$ echo '#!'`which python` > script.py
[ 14:35 jon@hozbox.com ~ ]$ chmod 755 script.py
[ 14:35 jon@hozbox.com ~ ]$ vi script.py

Then, in vim, add all the imports, main functions, etc...

To make life easier for those of us who create a few dozen python scripts every day, name this bash script mkpy and place it in your /home/MYUSER/bin/ directory:


#!/bin/bash

function makeFile() {
    printf \#\!/usr/bin/python\\n\#\ ${1}\\n\#\\n\#\ Author:\ `whoami`\\n\#\ Date:\ "$( date +%c )"\\n\#\\n\\nimport\ re\\nimport\ os\\nimport\ sys\\nimport\ socket\\nimport\ urllib\\n\\ndef\ main\(\):\\n\ \ \ \ \\n\\nif\ __name__\ ==\ \'__main__\':\\n\ \ \ \ sys.exit\(main\(\)\)\\n\\n > ${1}
    chmod 755 ${1}
    vim +15 ${1}

    # Un-comment this next line if you want the script to run the
    #  python script after you quit editing with vim.
    #  This will also pass any command line args through to the python script
    #
    #/usr/bin/python ${@}
}

if [ -a $1 ]; then
    echo -n "Overwrite ${1} [y/n]: "
    read overwrite
    if [ `echo "${overwrite:0:1}" | tr "Y" "y"` ==  "y" ]; then
        makeFile ${*}
    fi
else
    makeFile ${*}
fi

Then, it can be used with:


[ 14:35 jon@hozbox ~ ]$ mkpy mkpy_test_script.py

to automatically create an executable python script with the following code already written for you:


#!/usr/bin/python
# mkpy_test_script.py
#
# Author: jon
# Date: Sat Nov 12 14:35:09 2011
#

import re
import os
import sys
import socket
import urllib

def main():
   pass

if __name__ == '__main__':
    sys.exit(main())

Comments

Leave a Reply