Python optparse不工作-语法错误

Python optparse不工作-语法错误,python,syntax,optparse,Python,Syntax,Optparse,此脚本基于另一个用于分配的脚本。我的代码看起来和他们的一样,都有语法错误。我正在使用ActiveState Active Python 2.7 64位运行 def showEvents(): ''' showEvents command List events from event logger with the following options: -t or -type (type of event to search for) warning (d

此脚本基于另一个用于分配的脚本。我的代码看起来和他们的一样,都有语法错误。我正在使用ActiveState Active Python 2.7 64位运行

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')
它运行时返回默认值,但不接受输入。我错过了什么

>>> type =  warning
goBack = 100 hours
>>> showEvents -t error
Traceback (  File "<interactive input>", line 1
    showEvents -t error
                  ^
SyntaxError: invalid syntax
>>> 
>类型=警告
goBack=100小时
>>>showEvents-t错误
回溯(文件“”,第1行
showEvents-t错误
^
SyntaxError:无效语法
>>> 

感谢您的关注。

问题不在于您的代码,而在于您尝试测试它的方式

showEvents-t error
不是Python的有效行,但它是
sh
cmd
的有效行

因此,您不需要在Python解释器中键入它,而是在终端/DOS窗口中的bash/DOS提示符中键入它

此外,如果您不在Windows上,脚本必须另存为
showEvents
(而不是
showEvents.py
),并且必须安装在
路径的某个地方,并且必须设置可执行标志,并且需要
#!/usr/bin/env python
或类似的第一行。(或者您可以跳过所有这些,并在bash提示符下键入
python showEvents.py-t error


在Windows上,你可以称它为
showEvents.py
;只要你
cd
”保存在同一个目录中,它就会自动出现在你的
路径上;并且没有可执行的标志或shebang行需要担心。

你在什么平台上?我可以写一个一般性的答案,但具体的答案对于Windo来说会有所不同ws、Mac、linux等。此外,您的缩进显然是错误的。我想我已经修复了它,但请检查并确保它与您正在运行的内容相同。缩进只是在此处发布代码的产物。感谢您的查看。是的,粘贴到此处有时可能会有问题。您必须查看预览并确保其正确。非常好!不这也解释了为什么他们的任务也不起作用。设置此评估任务时,有一个最小的方向。此外,距离几乎没有支持。是的,编写的作业非常容易误导。docstring非常强烈地暗示,您将在Python提示符(
>>
)处键入此内容,而不是在DOS(
C:\>
)或者bash(
$
)提示符…这是我的文档字符串..根据我对请求的代码的理解,我现在必须修复它。