我有这个脚本:
#!/usr/bin/python
import sys
import ast
def main(argv):
for line in sys.stdin:
try:
rules, scores = line.split('\t')
scores = ast.literal_eval(scores)
print '\t'.join([rules, str(any(scores))])
except:
sys.stderr.write('Got line ' + line)
raise
if __name__ == "__main__":
main(sys.argv[0]) # 0 as there are no args besides the hive query fields
该脚本按预期的输入预期工作
$ echo -e "[{2,3},{4,3}]\t[1]" | ./check_anom.py
[{2,3},{4,3}] True
但是当输入错误时:
$ echo -e "[{2,3},{4,3}]\t" | ./check_anom.py
Got line [{2,3},{4,3}]
Traceback (most recent call last):
File "./check_anom.py", line 19, in <module>
main(sys.argv[0]) # 0 as there are no args besides the hive query fields
File "./check_anom.py", line 12, in main
scores = ast.literal_eval(scores)
File "/usr/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
^
SyntaxError: unexpected EOF while parsing
我本来会期望出现ValueError,为什么会出现SyntaxError?
答案 0 :(得分:2)
您似乎正在尝试eval("")
,因为您的[1]
所在的\t
后面没有split
。它在您的第一个命令中,而不是引发错误的命令。
加薪不会引起语法错误,eval("")
会导致语法错误,加薪只会引发它。