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?
The standard way to do this is to guard the code that should be only run when the script is called stand-alone by
The code after this
ifwon’t be run if the module is imported.The
__name__special variable contains the name of the current module as a string. If your file is calledglonk.py, then__name__will be"glonk"if the the file is imported as a module and it will be"__main__"if the file is run as a stand-alone script.