开发者

How do you make Python wait so that you can read the output?

I've always been a heavy user of Notepad2, as it is fast, feature-rich, and supports syntax highlighting. Recently I've been using it for Python.

My problem: when I finish editing a certain Python source code, and try to launch it, the screen disappears before I can see the output pop up. Is there any way for me to make the results wait so that I can read it, short of using an input() or time-delay function? Other开发者_如何转开发wise I'd have to use IDLE, because of the output that stops for you to read.

(My apologies if this question is a silly one, but I'm very new at Python and programming in general.)


If you don't want to use raw_input() or input() you could log your output (stdout, stderr) to a file or files.

You could either use the logging module, or just redirect sys.stdout and sys.stderr.

I would suggest using a combination of the logging and traceback if you want to log errors with their trace stack.

Something like this maybe:

import logging, traceback
logging.basicConfig(filename=r'C:\Temp\log.txt', level=logging.DEBUG)

try:
    #do some stuff
    logging.debug('I did some stuff!')
except SomeException:
    logging.error(traceback.format_exc())

Here's an example of redirecting stdout and stderr:

if __name__ == '__main__':
    save_out = sys.stdout  # save the original stdout so you can put it back later
    out_file = open(r'C:\Temp\out.txt', 'w')
    sys.stdout = out_file

    save_err = sys.stderr
    err_file = open(r'C:\Temp\err.txt', 'w')
    sys.stderr = err_file

    main()  #call your main function

    sys.stdout = save_out  # set stdout back to it's original object
    sys.stderr = save_err

    out_file.close()
    err_file.close()

I'm going to point out that this is not the easiest or most straight forward way to go.


This is a "problem" with Notepad2, not Python itself.

Unless you want to use input()/sleep (or any other blocking function) in your scripts, I think you have to turn to the settings in Notepad2 and see what that has to offer.


you could start in the command window. e.g.:

c:\tmp\python>main.py

adding raw_input() (or input() in py3k) at the end of your script will let you freeze it for until enter is pressed, but it's not a good thing to do.


You can add a call to raw_input() to the end of your script in order to make it wait until you press Enter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜