Tuesday, July 29, 2014

Automating tasks with Python

Today I had to create a large number of test data entities in JSON. Instead of cutting and pasting I decided to give Python a go and therefore I created a command line script to generate the test data I needed. I had to google everything I needed, as I have only seen Python a few times before, but I ended up creating a neat little script that works perfectly, although I could have used the language features for JSON probably.

Here is the script:

__author__ = 'Per-Oivin Andersen'

import getopt, sys, uuid, string, random, os


def usage():
    print "usage: provide count and number of orgunits and the file usage.xml will be generated."


def main():
    filename = "users.json"
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:v", ["help", "count="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    orgCount = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-c", "--count"):
            orgCount = a
        else:
            assert False, "unhandled option"
    if not orgCount.isdigit:
        usage()
        sys.exit()
    if int(orgCount) <= 0:
        usage()
        sys.exit()
    json ="["
    for num in range(1,int(orgCount)+1):
        id=uuid.uuid4()
        name=''.join(random.choice(string.ascii_letters) for _ in range(6))
        username=''.join(random.choice(string.ascii_letters) for _ in range(6))
        group=str(bool(random.getrandbits(1))).lower()
        json += "{" \
                "\n\"id\": \"%s\"," \
                "\n\t\"username\": \"%s\"," \
                "\n\t\"password\": \"password\"," \
                "\n\t\"isGroup\": %s," \
                "\n\t\"name\": \"%s\"" \
                "\n}" % (id,username,group,name)
        if num < int(orgCount):
            json += ",\n"
    json += "]"
    try:
        os.remove(filename)
    except OSError:
        pass
    file = open(filename, 'w+')
    file.write(json)
    print json
    print "\n\n JSON written to file " + filename

if __name__ == "__main__":
    main()

No comments:

Post a Comment