Programming

파이썬 스크립트 출력 창을 유지하는 방법?

procodes 2020. 5. 23. 23:09
반응형

파이썬 스크립트 출력 창을 유지하는 방법?


방금 파이썬으로 시작했습니다. Windows에서 Python 스크립트 파일을 실행하면 출력 창이 나타나지만 즉시 사라집니다. 출력을 분석 할 수 있도록 거기에 있어야합니다. 어떻게 열어 둘 수 있습니까?


몇 가지 옵션이 있습니다.

  1. 이미 열려있는 터미널에서 프로그램을 실행하십시오. 명령 프롬프트를 열고 다음을 입력하십시오.

    python myscript.py
    

    그것이 작동하려면 경로에 python 실행 파일이 필요합니다. Windows에서 환경 변수를 편집하는 방법을 확인하고 C:\PYTHON26파이썬을 설치 한 디렉토리를 추가하십시오 .

    프로그램이 끝나면 창을 닫는 대신 cmd 프롬프트로 돌아갑니다 .

  2. 스크립트가 끝날 때까지 기다리는 코드를 추가하십시오. Python2의 경우 ...

    raw_input()
    

    ... 스크립트 끝에서 Enter키를 기다립니다 . 이 방법은 스크립트를 수정해야하고 작업이 끝나면 제거해야한다는 점에서 성가신 일입니다. 다른 사람의 스크립트를 테스트 할 때 특히 성가시다. Python3의 경우을 사용하십시오 input().

  3. 일시 중지 된 편집기를 사용하십시오. 파이썬을 위해 준비된 일부 편집기는 실행 후 자동으로 일시 중지됩니다. 다른 편집기를 사용하면 프로그램을 실행하는 데 사용하는 명령 줄을 구성 할 수 있습니다. python -i myscript.py실행할 때 " " 로 구성하는 것이 특히 유용합니다 . 프로그램 종료 후 프로그램 환경이로드 된 상태에서 파이썬 쉘로 넘어가므로 변수를 가지고 연주하고 함수와 메소드를 호출 할 수 있습니다.


cmd /k응용 프로그램을 닫은 후에도 유지되는 콘솔 창으로 콘솔 응용 프로그램 (Python뿐만 아니라)을 여는 일반적인 방법입니다. 내가 생각할 수있는 가장 쉬운 방법은 Win + R을 누르고 cmd /k원하는 스크립트를 입력 한 다음 실행 대화 상자에 끌어다 놓는 것입니다.


이미 열린 cmd 창에서 스크립트를 시작하거나 스크립트 끝에서 다음과 같이 Python 2에서 다음을 추가하십시오.

 raw_input("Press enter to exit ;)")

또는 파이썬 3에서 :

input("Press enter to exit ;)")

예외가 발생한 경우 창을 열어 두려면 (아직 예외를 인쇄하는 동안)

파이썬 2

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
        print "Press Enter to continue ..." 
        raw_input() 

어떤 경우에도 창을 열어 두려면 :

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except Exception:
        import sys
        print sys.exc_info()[0]
        import traceback
        print traceback.format_exc()
    finally:
        print "Press Enter to continue ..." 
        raw_input()

파이썬 3

Python3의 경우 input()대신 대신 사용해야raw_input() 하고 print명령문을 조정해야 합니다.

if __name__ == '__main__':
    try:
        ## your code, typically one function call
    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
        print("Press Enter to continue ...")
        input() 

어떤 경우에도 창을 열어 두려면 :

if __name__ == '__main__':
    try:
        ## your code, typically one function call
except BaseException:
    import sys
    print(sys.exc_info()[0])
    import traceback
    print(traceback.format_exc())
finally:
    print("Press Enter to continue ...")
    input()

당신은 전에 답변을 결합 할 수 있습니다 : (Notepad ++ 사용자의 경우)

F5를 눌러 현재 스크립트를 실행하고 명령을 입력하십시오.

cmd /k python -i "$(FULL_CURRENT_PATH)"

in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)


Create a Windows batch file with these 2 lines:

python your-program.py

pause

In python 2 you can do it with: raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

In python 3 you can do it with: input()

>>print("Hello world!")    
>>input('Waiting a key...')

Also, you can do it with the time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

Using atexit, you can pause the program right when it exits. If an error/exception is the reason for the exit, it will pause after printing the stacktrace.

import atexit

# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')

In my program, I put the call to atexit.register in the except clause, so that it will only pause if something went wrong.

if __name__ == "__main__":
    try:
        something_that_may_fail()

    except:
        # Register the pause.
        import atexit
        atexit.register(input, 'Press Enter to continue...')

        raise # Reraise the exception.

I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.


On Python 3

input('Press Enter to Exit...')

Will do the trick.


To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs.

This would just show a cursor with no text:

raw_input() 

This next example would give you a clear message that the program is done and not waiting on another input prompt within the program:

print('You have reached the end and the "raw_input()" function is keeping the window open') 
raw_input()

Note!
(1) In python 3, there is no raw_input(), just input().
(2) Use single quotes to indicate a string; otherwise if you type doubles around anything, such as "raw_input()", it will think it is a function, variable, etc, and not text.

In this next example, I use double quotes and it won't work because it thinks there is a break in the quotes between "the" and "function" even though when you read it, your own mind can make perfect sense of it:

print("You have reached the end and the "input()" function is keeping the window open")
input()

Hopefully this helps others who might be starting out and still haven't figured out how the computer thinks yet. It can take a while. :o)


If you want to run your script from a desktop shortcut, right click your python file and select Send to|Desktop (create shortcut). Then right click the shortcut and select Properties. On the Shortcut tab select the Target: text box and add cmd /k in front of the path and click OK. The shortcut should now run your script without closing and you don't need the input('Hit enter to close')

Note, if you have more than one version of python on your machine, add the name of the required python executable between cmd /k and the scipt path like this:

cmd /k python3 "C:\Users\<yourname>\Documents\your_scipt.py"

Apart from input and raw_input, you could also use an infinite while loop, like this: while True: pass (Python 2.5+/3) or while 1: pass (all versions of Python 2/3). This might use computing power, though.

You could also run the program from the command line. Type python into the command line (Mac OS X Terminal) and it should say Python 3.?.? (Your Python version) It it does not show your Python version, or says python: command not found, look into changing PATH values (enviromentl values, listed above)/type C:\(Python folder\python.exe. If that is successful, type python or C:\(Python installation)\python.exe and the full directory of your program.


A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:

python.exe %1
@echo off
echo.
pause

and then specified pythonbat.bat as the default handler for .py files.

Now, when I double-click a .py file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...

No changes required to any Python scripts.

I can still open a console window and specify python myscript.py if I want to...

(I just noticed @maurizio already posted this exact answer)


You can open PowerShell and type "python". After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.

The window won't close.


  1. Go here and download and install Notepad++
  2. Go here and download and install Python 2.7 not 3.
  3. Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  4. Close Powershell and reopen it.
  5. Make a directory for your programs. mkdir scripts
  6. Open that directory cd scripts
  7. In Notepad++, in a new file type: print "hello world"
  8. Save the file as hello.py
  9. Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
  10. At the Powershell prompt type: python hello.py

A simple hack to keep the window open:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

The counter is so the code won’t repeat itself.


On windows 10 insert at beggining this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Strange, but it work for me!(Together with input() at the end, of course)

참고URL : https://stackoverflow.com/questions/1000900/how-to-keep-a-python-script-output-window-open

반응형