0

I have a script in Python 2.7 converted in executable with py2exe. The INPUT data is a text file where the delimiter need to be valid following this function:

# 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!")

When the delimiter is not valid (ex: a dot) i am looking for two solution in a Python elegant way:

  • Until the right INPUT data is not load you can not pass to OUTFILE

or

  • The script break the code, show the error, but the windows (when is a *.exe) doesn't close immediately leaving the user without an explanation

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): ")

with this solution (break) the Window of my *.exe file close leaving the user without an explanation

freakish
  • 54,167
  • 9
  • 132
  • 169
Gianni Spear
  • 7,033
  • 22
  • 82
  • 131
  • Thanks Freakish, but the second time of INPUT you go to OUTPUT :) – Gianni Spear Apr 05 '13 at 15:43
  • possible duplicate of [How to keep a Python script output window open?](http://stackoverflow.com/questions/1000900/how-to-keep-a-python-script-output-window-open) – Kevin Apr 05 '13 at 16:47

2 Answers2

1

You can hook the exception handler for uncaught exceptions using sys.excepthook, and have it call raw_input() (or input() in 3.x) as per this answer.

For a quick example:

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

Just modify that to have whatever output or whatever you want (I suggest looking into the traceback module).

But if you want it more specific to your code, then just put raw_input("Press any key to exit...") in the solution you already have, and it should be fine. The above should provide a more general solution.

Community
  • 1
  • 1
Poik
  • 2,022
  • 27
  • 44
  • a possible solution is add: raw_input("press any key to exit")
    print "Exiting....."
    break
    – Gianni Spear Apr 05 '13 at 17:34
  • @Gianni - They'll never see that last `"Exiting....."` since [`sys.excepthook` is only called when the whole stack is unwound and no exception handler was found, just before the program would exit.](http://stackoverflow.com/a/11365708/786020) It would print and quit too fast for the user to see, which was your original problem. – Poik Apr 05 '13 at 17:41
  • Hey Poik thanks for your suggestion, I got the point. I think (from my software design point of view) it's important that the user understand that the text file has a delimiter not valid. The text file is floating number and using "." as delimiter can be a problem. I want to avoid this/ – Gianni Spear Apr 05 '13 at 17:47
  • 1
    @Gianni - Right. I was just helping with the programmatic side. It's up to you to help your users. :3 If there's a specific point I missed, or something else I can help with, don't hesitate to ask. – Poik Apr 05 '13 at 17:51
  • another solution is change get_parse in order to get the delimiter and use the condition while parse == ".": – Gianni Spear Apr 05 '13 at 18:10
1

You are not really searching for a delimiter, just a character in a string. You should really use the CSV module for this.

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()
serk
  • 4,329
  • 2
  • 25
  • 38
  • a possible solution is add: raw_input("press any key to exit")
    print "Exiting....."
    break
    – Gianni Spear Apr 05 '13 at 17:36
  • That's not a possible solution to what you asked for: `"Until the right INPUT data is not load you can not pass to OUTFILE"` AND `"The script break the code, show the error, but the windows (when is a *.exe) doesn't close immediately leaving the user without an explanation"`. Yes, if all you wanted to do was keep the window open after the error occurred, a `raw_input('...')` would suffice, however you also asked that nothing happen unless the correct input file was loaded. With the code snippet I provided, nothing will happen until it has a file with the `txt` extension (which met your reqs). – serk Apr 05 '13 at 21:29