python - Allowing Module/package customization with command line paramters without interfering with its users -
i'm curious how in python. imagine have module spam.py i'd control spamminess option --spam_more.
how go using argparse or other parsing library still allow main ham.py file optionally use command line arguments while using spam module.?
you can put argument handling stuff inside 'if __name__ == "__main__":' code inside if block run when script run command line or whatever, not if imported module. e.g. typing $ python spam.py in command line cause block executed.
here example using optparse (because haven't used argparse before):
spam.py:
def do_stuff(spammy=false): if spammy: print "wow, spammy." else: print "i've seen spammier." if __name__ == "__main__": optparse import optionparser p = optionparser() p.add_option("--spam_more", action="store_true", dest="spammy") (options, args) = p.parse_args() do_stuff(options.spammy) ham.py:
import spam # optparse stuff... spam.do_stuff() this when use --spam_more on spam.py, spammy set true. ham.py knows nothing , can use it's own optparse stuff use use spam's function, do_stuff() because code inside 'if __name__ == "__main__":' never gets run when spam.py imported module.
it bad practice put import statement inside if block, seems best way.
Comments
Post a Comment