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.

1
  • Do this, please. First, read PEP 8: python.org/dev/peps/pep-0008. Second, after reading, update your question to mention specific things you didn't understand in PEP-8. This is already answered in PEP 8. Commented Aug 1, 2010 at 14:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

great, exactly what I was looking for.
what about args that you pass when calling the script from command line?
@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.
+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!

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.