Can you make a python script behave differently when imported than when run directly?
- by futuraprime
I often have to write data parsing scripts, and I'd like to be able to run them in two different ways: as a module and as a standalone script. So, for example:
def parseData(filename):
# data parsing code here
return data
def HypotheticalCommandLineOnlyHappyMagicFunction():
print json.dumps(parseData(sys.argv[1]), indent=4)
the idea here being that in another python script I can call import dataparser and have access to dataParser.parseData in my script, or on the command line I can just run python dataparser.py and it would run my HypotheticalCommandLineOnlyHappyMagicFunction and shunt the data as json to stdout. Is there a way to do this in python?