Can you make a python script behave differently when imported than when run directly?
Posted
by
futuraprime
on Stack Overflow
See other posts from Stack Overflow
or by futuraprime
Published on 2012-04-08T17:27:23Z
Indexed on
2012/04/08
17:28 UTC
Read the original article
Hit count: 197
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?
© Stack Overflow or respective owner