我正在开发一个程序,它将从如下文件中提取文本:
NAME OF PROGRAM: text.txt
CONTENTS OF FILE:
1: 101010100101010101 1010010101010101 101010101010101
2: 0101010101 1010011010 10101010 10101010 10101010
3: 0001000101010 10101010 10101010 1010101010 10101
START LINE: 1
END LINE: 2
results.txt generated.
我在程序要求提供程序名称的部分,我计划在程序名称长度为零时使用异常。
该程序应该像:
NAME OF PROGRAM:
THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN 1! [LEN_ERROR]
但程序运行如此:
NAME OF PROGRAM:
THERE'S SOMETHING WRONG WITH YOUR INPUT! [INP_ERROR]
以下是代码:
class Program:
"""
Author : Alexander B. Falgui (alexbfalgui.github.io)
Program Name : Text Extractor
Description : Takes an integer or string as an input and generates a
text file with the extracted data.
Note: This program can be used, shared, modified by anyone.
"""
def __init__(self):
self.menu_file_loc = "menu"
return self.load_files()
def load_files(self):
#self.menu_file = open(self.menu_file_loc)
#self.read_mf = self.menu_file.read()
return self.main_menu()
def main_menu(self):
#print(self.read_mf)
print(""" [1] Extract Data\n [2] Exit""")
while (True):
try:
self.menu_input = input("CHOOSE AN OPTION> ")
if (self.menu_input == 1):
try:
self.program_name = raw_input("\nNAME OF THE PROGRAM: ")
self.program_name = open(self.program_name)
except IOError:
if (len(program_name) == 0):
print("THE NAME OF THE PROGRAM SHOULD NOT BE LESS THAN"),
print(" 1! [LEN_ERROR]")
print("%s does not exist" % self.program_name)
elif (self.menu_input == 0):
print("\n")
break
except SyntaxError:
continue
except NameError:
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
# Run the program
Program()
为什么程序会打印错误的异常,我该怎么做才能解决这个问题?
答案 0 :(得分:0)
请不要except SyntaxError: continue
,因为您会默默地检查任何语法错误。
要获得有关出错的更多信息,您应except NameError as e
进一步调查。另请参阅https://docs.python.org/2/tutorial/errors.html
您应该将except NameError
- 部分更改为以下内容:
except NameError as e:
print e
print("SOMETHING'S WRONG WITH YOUR INPUT. [INP_ERROR]\n")
你会看到出了什么问题。
答案 1 :(得分:0)
我不确定为什么你在最后添加了这两个异常处理程序,但是你得到了一个名称异常,因为你引用了 program_name 变量而不是 self.program_name
将您的专线if (len(program_name) == 0):
更改为if (len(self.program_name) == 0):
,它应该有效。