如何在程序完成执行时阻止命令窗口关闭

时间:2012-11-08 01:17:06

标签: python command-line py2exe command-window

我在Python(.py)中创建了一个小程序,并使用Py2exe将其转换为Windows可执行文件(.exe)。它要求一个字符串,然后输出一个字符串 - 非常简单! - 并且在Python中完美运行。

然而,当exe文件在命令窗口中完成执行时,命令窗口会自动关闭,然后才能看到它的输出(我假设它确实打印输出,因为就像我说的那样,它在Python中运行完美)

如何防止这种情况发生?我假设我需要更改我的代码,但我究竟需要添加什么呢?

这是我的代码,万一它可以帮助你看到它(它是一个自动换行器):

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)

谢谢。

3 个答案:

答案 0 :(得分:1)

最简单的方法可能是在程序完成之前使用raw_input()。它将一直等到你在关闭前点击进入。

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()

答案 1 :(得分:1)

将它放在代码的末尾:

junk = raw_input ("Hit ENTER to exit: ")

换句话说,您的main细分受众群应为:

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)
    junk = raw_input ("Press ENTER to continue: ")

答案 2 :(得分:0)

这是我在脚本中使用的内容:

#### windows only ####
import msvcrt

def readch(echo=True):
    "Get a single character on Windows."
    while msvcrt.kbhit():
        msvcrt.getch()
    ch = msvcrt.getch()
    while ch in b'\x00\xe0':
        msvcrt.getch()
        ch = msvcrt.getch()
    if echo:
        msvcrt.putch(ch)
    return ch.decode()

def pause(prompt='Press any key to continue . . .'):
    if prompt:
        print prompt,
    readch()
######################

有时候,我只是使用以下内容使窗口在关闭前保持打开一小段时间。

import time
time.sleep(3)