0

我有一个用 py2exe 转换为可执行文件的 Python 2.7 脚本。INPUT 数据是一个文本文件,其中分隔符需要在此函数之后有效:

# Check if delimeter is valid
def get_parse(filename, delimiters=['\t', ',', ' ', ':', ';', '-']):
    with open(filename) as f:
        f.next()
        secondline = f.next()
    for delimiter in delimiters:
        if len(secondline.rstrip().split(delimiter)) >= 3:
            return delimiter
    raise Exception("couldn't find a delimiter that worked!")

当分隔符无效时(例如:一个点),我正在以 Python 优雅的方式寻找两种解决方案:

  • 在未加载正确的 INPUT 数据之前,您不能将其传递给 OUTFILE

或者

  • 脚本破坏了代码,显示错误,但窗口(什么时候是 *.exe)没有立即关闭,让用户没有解释

INPUT = raw_input("Input (*.txt): ")
while not os.path.exists(INPUT):
      print IOError("No such file or directory: %s" % INPUT)
      INPUT = raw_input("Input (*.txt): ")
try:
    parse = get_parse(INPUT)
except Exception:
    print ValueError("Delimiter type not valid")
    break
OUTPUT = raw_input("Output (*.txt): ")

使用此解决方案(中断)我的 *.exe 文件的窗口关闭,使用户没有解释

4

2 回答 2

1

您可以使用 钩住未捕获异常的异常处理程序,并按照此答案sys.excepthook调用raw_input()(或在 3.x 中) 。input()

举个简单的例子:

import sys
def wait_on_uncaught_exception(type, value, traceback):
    print 'My Error Information'
    print 'Type:', type
    print 'Value:', value
    print 'Traceback:', traceback
    raw_input("Press any key to exit...")
sys.excepthook=wait_on_uncaught_exception

只需修改它以获得任何输出或任何你想要的(我建议查看traceback模块)。

但是,如果您希望它更具体到您的代码,那么只需放入raw_input("Press any key to exit...")您已有的解决方案,它应该没问题。以上应该提供更通用的解决方案。

于 2013-04-05T17:12:19.617 回答
1

您实际上并不是在搜索分隔符,而只是在搜索字符串中的一个字符。你真的应该为此使用 CSV 模块。

from __future__ import print_function

delimiters=['\t', ',', ' ', ':', ';', '-']

def getfile():
    fname =""
    while fname is "":
            fname = str.lower(raw_input("Input(*.txt): "))
            while fname.endswith(".txt") is not True:
                    print ("File must be .txt")
                    fname = str.lower(raw_input("Input(*.txt): "))
            if fname.endswith(".txt"):
                try:
                    with open(fname,'rb') as f:
                        parsed = False
                        while not parsed:
                            data = f.readline()
                            for d in delimiters:
                                if d in data:
                                    print ("Delimiter: {0} found".format(d))
                                    parsed = True
                                    # do your additional stuff here
                                else:
                                    print ("Unable to find delimiter {0}".format(d))
                                    parsed = True
                except IOError as e:
                    print( "Error: ", e)

getfile()
于 2013-04-05T17:29:07.940 回答