Search code examples
pythoncommand-linepy2execommand-window

How to prevent command window from closing when a program finishes executing


I made a small program in Python (.py) and converted it into a Windows executable file (.exe) using Py2exe. It asks for a string and then outputs a string -- very simple! -- and works flawlessly in Python.

However, when the exe file finishes execution in the command window, the command window closes automatically before I can get a glimpse of its output (I assume it does print the output because, like I said, it works flawlessly in Python).

How can I prevent this from happening? I assume I need to change my code, but what exactly do I need to add to it?

Here is my code, in case it helps you to see it (it's a word-wrapper):

import string

def insertNewlines(text, lineLength):
    if text == '':
        return ''
    elif len(text) <= lineLength:
        return text
    elif text[lineLength] == ' ':
        return text[:lineLength] + '\n' + insertNewlines(text[lineLength+1:], lineLength)
    elif text[lineLength-1] == ' ':
        return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)
    else:
        if string.find(text, ' ', lineLength) == -1:
            return text
        else:
            return text[:string.find(text,' ',lineLength)+1] + '\n' + insertNewlines(text[string.find(text,' ',lineLength)+1:], lineLength)
    print

if __name__ == '__main__':
    text = str(raw_input("Enter text to word-wrap: "))
    lineLength = int(raw_input("Enter number of characters per line: "))
    print 
    print insertNewlines(text, lineLength)

Thank you.


Solution

  • The simplest way is probably to use raw_input() just before your program finishes. It will wait until you hit enter before closing.

    if __name__ == '__main__':
        text = str(raw_input("Enter text to word-wrap: "))
        lineLength = int(raw_input("Enter number of characters per line: "))
        print 
        print insertNewlines(text, lineLength)
        raw_input()