Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 592
futuraprime Avatar asked Mar 18 '26 21:03

futuraprime


1 Answers

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.

like image 173
Sven Marnach Avatar answered Mar 21 '26 09:03

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!