开发者

script as module and executable

开发者 https://www.devze.com 2023-01-09 15:59 出处:网络
I have a script in python that can be invoked from the command-line and uses optparse. script -i arg1 -j arg2
  • 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 create options then use options.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.'
0

精彩评论

暂无评论...
验证码 换一张
取 消