script as module and executable
I have a script in python that can be invoked from the command-line and uses
optparse
.script -i arg1 -j arg2
In this case I use
(options, args) = parser.parse_args()
to createoptions
then useoptions.arg1
to get arguments.But I also want it to be importable as a module.
from script import * function(arg1=a开发者_JS百科rg1, arg2=arg2)
I've managed to do this using a really lame solution: by providing a dummy object.
def main(): class Options: ''' dummy object ''' def __init__(self): pass options = Options for k in kwargs: setattr(options, k, kwargs[k])
The rest of the script doesn't know the difference but I think this solution is fugly.
Is there a better solution to this?
Separate the CLI from the workhorse class:
class Main(object):
def __init__(self,arg1,arg2):
...
def run(self):
pass
if __name__=='__main__':
import optparse
class CLI(object):
def parse_options(self):
usage = 'usage: %prog [options]'+__usage__
parser = optparse.OptionParser(usage=usage)
parser.add_option('-i', dest='arg1')
parser.add_option('-j', dest='arg2')
(self.opt, self.args) = parser.parse_args()
def run(self):
self.parse_options()
Main(self.opt.arg1,self.opt.arg2).run()
CLI().run()
What you usually do is:
def foo():
print 'This is available when imported as a module.'
if __name__ == '__main__':
print 'This is executed when run as script, but not when imported.'
精彩评论