60
if len(sys.argv) < 2:
    sys.stderr.write('Usage: sys.argv[0] ')
    sys.exit(1)


if not os.path.exists(sys.argv[1]):
    sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
    sys.exit(1)

This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type python programname something then it will exit.

The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.

Serenity
  • 35,289
  • 20
  • 120
  • 115
Tyler
  • 3,919
  • 7
  • 27
  • 26

3 Answers3

100

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
Marius Gedminas
  • 11,010
  • 4
  • 41
  • 39
34

In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:

sys.stderr.write("Usage: " + sys.argv[0])

or

sys.stderr.write("Usage: %s" % sys.argv[0])

Also, you may want to consider using the following syntax of print (for Python earlier than 3.x):

print >>sys.stderr, "Usage:", sys.argv[0]

Using print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.

In Python 3.x, you would use the print function:

print("Usage:", sys.argv[0], file=sys.stderr)

Finally, in Python 2.6 and later you can use .format:

print >>sys.stderr, "Usage: {0}".format(sys.argv[0])
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
32

I would do it this way:

import sys

def main(argv):
    if len(argv) < 2:
        sys.stderr.write("Usage: %s <database>" % (argv[0],))
        return 1

    if not os.path.exists(argv[1]):
        sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
        return 1

if __name__ == "__main__":
    sys.exit(main(sys.argv))

This allows main() to be imported into other modules if desired, and simplifies debugging because you can choose what argv should be.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
  • This is a nice explanation - I was looking for more information on using sys.exit( main(sys.argv) ) and why it was encouraged. Thanks for the explanation. – Helen Neely Feb 28 '10 at 22:46