views:

46

answers:

2

This is more a question of coding style, but I have a script that processes a particular file (or set of files). It would be nice to allow the user to provide those files as command-line arguments. Of course, it's possible that the user forgets to provide these or the filenames are invalid, so I have to introduce a try/except here.

Problem is, someone may want to import my module in the future. But, I don't know what command line arguments that program may require. Also, if an error is thrown when my module access the command-line argument, it seems like it would be better handled by the script that is importing my module. However, my script still needs to be able to cope as a stand-alone if an error is thrown.

Is there a smart way around this problem, or is the best solution just to abandon command-line arguments altogether?

+1  A: 

Check if your file is being run or if it's imported thus:

def myFunction(file):
  #do stuff to file

if __name__ == '__main__':
  #I have not been imported!
  try:
    file = sys.argv[1]
  except:
    print "Usage: myFile.py file"
    sys.exit()
  myFunction(file)
fredley
+4  A: 

The usual procedure:

import sys

def main(*files):
    # your program's logic goes here

if __name__ == "__main__": #i.e. run directly
    try:
        main(*sys.argv[1:])
    except IOError:
        handle_error()

If imported, __name__ will be != "__main__", thus nothing actually happens and the importer can call main(file1, file2). But if this script is the main script (i.e. not imported), it will just do what it does now, only in main.

delnan