Can you make a python script behave differently when imported than when run directly?

python

Solution

The standard way to do this is to guard the code that should be only run when the script is called stand-alone by

if __name__ == "__main__":
    # Your main script code

The code after this `if` won'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 called `glonk.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.

Problem

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?

Original source