Home > Blockchain >  Python script pausing in cmd
Python script pausing in cmd

Time:08-26

I am running a few Python scripts at the same time. They are running in windows CMD.

I never knew that you can externally pause a Python script running in CMD.

If I hold the mouse button for a few seconds the script pauses and not just the output the execution as well.

For simplicity's sake I am showing you a very simple example:

while datetime.datetime.now().hour < 16:
    print(datetime.datetime.now())
    with open("dump.txt", "at") as f:
        f.write(f"t: {datetime.datetime.now()}\n")
    time.sleep(5)

Both the output to the file and the print to stdout stop if I squeeze the mouse button and they restart when I press enter.

I have two questions, how can I run Python that this type of stops are not possible?

The other is if there some way to detect this type of event in Python(at least the restart).

CodePudding user response:

This happens if the "Quick Edit Mode" of the console is enabled. To temporarily disable use following code (error checks missing for brevity):

import win32console as con
import signal


# Missing constants in pywin

ENABLE_EXTENDED_FLAGS = 0x0080
ENABLE_QUICK_EDIT_MODE = 0x0040 


h = con.GetStdHandle(con.STD_INPUT_HANDLE)
oldMode = h.GetConsoleMode()

# Restore old console mode on CTRL-C 
def handler(signum, frame):
    h.SetConsoleMode(oldMode)
    exit()

signal.signal(signal.SIGINT, handler)


# Modify console mode to disable quick edit mode
h.SetConsoleMode((oldMode | ENABLE_EXTENDED_FLAGS) &
        ~ENABLE_QUICK_EDIT_MODE)


# Test
while True:
    print("a", end="")

# Final mode restore (never reached in this example)
h.SetConsoleMode(oldMode)

Based on documentation:

http://timgolden.me.uk/pywin32-docs/win32console__GetStdHandle_meth.html
http://timgolden.me.uk/pywin32-docs/PyConsoleScreenBuffer__GetConsoleMode_meth.html
http://timgolden.me.uk/pywin32-docs/PyConsoleScreenBuffer__SetConsoleMode_meth.html

https://docs.microsoft.com/en-us/windows/console/setconsolemode

http://www.gaclib.net/CodeIndexDemo/Gaclib/SourceFiles/consoleapi.h.html

CodePudding user response:

It's actually the cmd.exe entering the so called quick edit mode to help users select the text output. here is a good explanation about that.

you can disable it for yourself via properties of cmd.exe, read here, how - (it required a restart of cmd for me).

  • Related