1
  • 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=arg1, 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?

2
  • 3
    for k in **kwargs:? can you paste the actual code you are using? Commented Jul 27, 2010 at 21:25
  • 1
    That's actually not a bad solution. Just FYI though, you can remove the init and just have "class Options: pass". I've often wondered why Python doesn't come with a built-in "null class" that lets you set any attributes on it, as you can't do with a plain object(). Commented Jul 27, 2010 at 21:29

2 Answers 2

6

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()
Sign up to request clarification or add additional context in comments.

Comments

2

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.'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.