tags:

views:

48

answers:

1

Just need some clarification on how to design a python script file test.py.

  1. When defining functions, do they have to go on the top of the file right after the imports?

  2. should I be doing that main check in my file?

  3. I want to run this file on my server as a cron job. If the file gets too big (I have my sqlalchemy definitions in it also), how can I break the file into multiple files? I want this easy to deploy by just dropping the files into a folder in my server.

+2  A: 

Most scripts look something like the following:

import module1
import module2

CONSTANT=...

def foo():
   ...

def bar():
   ....

class Baz():
   ....

def run(verbose=False):
    ....

if __name__=='__main__':
    import optparse
    def parse_options():
        usage = 'usage: %prog [options]'
        parser = optparse.OptionParser(usage=usage)
        parser.add_option('-v', '--verbose', dest='verbose',
                          action='store_true', 
                          default=False,
                          help="verbose")
        return parser.parse_args()
    def cli():
        opt,args=parse_options()        
        run(verbose=opt.verbose)
    cli()

So the body of your script is mainly composed of function/class definitions. There (usually) is very little code that isn't inside a function/class definition.

I would try to group the functions in whatever way facilitates organization and readability. If you believe a function can be reused in places other than that particular script, then place it in a module, and import that module into this script.

Define PYTHONPATH and PATH in your crontab. Then you should have no problem running your script from cron.

unutbu
great, exactly what I was looking for.
Blankman
what about args that you pass when calling the script from command line?
Blankman
@Blankman: I use the `optparse` module from the standard library to handle arguments from the command line. If you use Python2.7 or better, you might want to consider the `argparse` module which I believe is intended to replace optparse. I'll edit my answer to show the structure for optparse.
unutbu
+100 awesome, I was thinking of adding a 'verbose' option, so bascially I can output print statements if verbose is set right? thanks a bunch!
Blankman