파이썬

윈도우 환경에서 파이썬 스크립트를 백그라운드 실행

디다새 2021. 5. 11. 13:29

Windows에서는 pythonw.exe 실행 파일을 사용하여 백그라운드에서 Python 스크립트를 실행할 수 있습니다. 이렇게하면 눈에 보이는 프로세스나 상호 작용하는 방법없이 백그라운드에서 프로그램이 실행됩니다. 시스템 모니터없이 종료 할 수도 없습니다. pythonw.exe에 대한 자세한 내용은 다음을 참조하세요. 

 

참조 페이지 : https://stackoverflow.com/questions/32808730

 

https://stackoverflow.com/questions/9705982/pythonw-exe-or-python-exe

 

To summarize and complement the existing answers:

  • python.exe is a console (terminal) application for launching CLI-type scripts.
    • Unless run from an existing console window, python.exe opens a new console window.
    • Standard streams sys.stdinsys.stdout and sys.stderr are connected to the console window.
    • Execution is synchronous when launched from a cmd.exe or PowerShell console window: See eryksun's 1st comment below.
      • If a new console window was created, it stays open until the script terminates.
      • When invoked from an existing console window, the prompt is blocked until the script terminates.
  • pythonw.exe is a GUI app for launching GUI/no-UI-at-all scripts.
    • NO console window is opened.
    • Execution is asynchronous:
      • When invoked from a console window, the script is merely launched and the prompt returns right away, whether the script is still running or not.
    • Standard streams sys.stdinsys.stdout and sys.stderr are NOT available.
      • CautionUnless you take extra steps, this has potentially unexpected side effects:
        • Unhandled exceptions cause the script to abort silently.
        • In Python 2.x, simply trying to use print() can cause that to happen (in 3.x, print() simply has no effect. --> print() is simply  ignored).
        • To prevent that from within your script, and to learn more, see this answer of mine.
        • Ad-hoc, you can use output redirection:Thanks, @handle.
          pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt
          (from PowerShell:
          cmd /c pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt) to capture stdout and stderr output in files.
          If you're confident that use of 
          print() is the only reason your script fails silently with pythonw.exe, and you're not interested in stdout output, use @handle's command from the comments:
          pythonw.exe yourScript.pyw 1>NUL 2>&1
          Caveat: This output redirection technique does not work when invoking *.pyw scripts directly (as opposed to by passing the script file path to pythonw.exe). See eryksun's 2nd comment and its follow-ups below.

 

You can control which of the executables runs your script by default - such as when opened from Explorer - by choosing the right filename extension:

  • *.py files are by default associated (invoked) with python.exe
  • *.pyw files are by default associated (invoked) with pythonw.ex