Search code examples
pythonsyntaxoptparse

Python optparse not working - syntax error


this script is based on another for an assignment. My code looks the same as theirs and BOTH error out with a syntax error. I am running with ActiveState Active Python 2.7 64-bit

def showEvents():
    ''' showEvents command

    List events from event logger with the following options:
    -t or -type (type of event to search for)
        warning (default option)
        error 
        information
        all
    -g or -goback (time in hours to search)
        integer
        default is 100 hours

    >>>showEvents -t warning -g 100
    type =  warning
    goBack = 100 hours
    '''
    import optparse

    parser = optparse.OptionParser()
    parser.add_option('-t', '--type', \
                        choices=('error', 'warning', 'information', 'all' ), \
                        help='write type to eventType', 
                        default = 'warning')
    parser.add_option('-g', '--goback', \
                        help='write goback to goback',
                        default = '100')
    (options, args) = parser.parse_args()
    return options

options = showEvents()

print 'type = ', options.type
print 'goBack =', options.goback, 'hours'

if options.type == 'all':
if options.goback == '24':
    import os
    os.startfile('logfile.htm')

This returns the defaults when it runs, but it wont accept input. What have I missed?

>>> type =  warning
goBack = 100 hours
>>> showEvents -t error
Traceback (  File "<interactive input>", line 1
    showEvents -t error
                  ^
SyntaxError: invalid syntax
>>> 

Thanks for looking.


Solution

  • The problem isn't with your code, but with the way you're trying to test it.

    showEvents -t error is not a valid line of Python, but it is a valid line of sh or cmd.

    So, you don't type it into the Python interpreter, you type it into the bash/DOS prompt in a Terminal/DOS window.

    Also, if you're not on Windows, the script will have to be saved as showEvents (rather than showEvents.py), and it will have to be installed somewhere on your PATH, and it will have to have the executable flag set, and it will need a #!/usr/bin/env python or similar first line. (Or you can skip all that and type python showEvents.py -t error at the bash prompt.)

    On Windows, you can call it showEvents.py; as long as you're cd'd to the same directory it's saved in it's automatically on your PATH; and there is no executable flag or shebang line to worry about.