此脚本基于另一个用于作业。我的代码看起来与他们的相同,并且BOTH错误输出语法错误。我正在运行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
>>>
感谢您的光临。
答案 0 :(得分:2)
问题不在于您的代码,而在于您尝试测试它的方式。
showEvents -t error
不是有效的Python行,但 是sh
或cmd
的有效行。
因此,您不要在Python解释器中键入它,在终端/ DOS窗口中将其键入bash / DOS提示符。
此外,如果您不在Windows上,则必须将脚本保存为showEvents
(而不是showEvents.py
),并且必须将其安装在{{1}上的某个位置它必须设置可执行标志,并且需要PATH
或类似的第一行。 (或者您可以跳过所有这些并在bash提示符下键入#!/usr/bin/env python
。)
在Windows上,您可以将其称为python showEvents.py -t error
;只要你showEvents.py
'到同一个目录,它就会自动保存在cd
;并且没有可执行标志或shebang线担心。