简体   繁体   中英

What is the best way to pause/stop/command a Python script anytime anywhere?

I have a Python script running selenium framework in a command line and running continuously to control Chrome do background data processing and monitoring. My simplified code structure is as following

while True:
    Do_task1() # a blocking function
    Do_task2() # another blocking fucntion
    ... # calling many blocking functions below, including wait(), time.sleep()

I need a way to interrupt the script anytime and anywhere to pause, terminate safely and give commands. What are the best ways to do this? I've thought and tried of several ways but I am not exactly sure how to approach it:

  1. I tried this:

     if msvcrt.kbhit(): key = msvcrt.getch().decode("utf-8").lower() if key == "j": self.setting1 = True elif key == "k": self.setting2 = True 

    in the while loop, but it has to pass through bunch of blocking calls before reacting to my keypresses. And the command isn't exactly accepting my keyboard input in real time, that is I'll enter a character input, and I think it will be in the background buffer, then once the code execution reaches the code above, it starts to do stuff. For terminating the script, I just do Ctrl-C in the CMD window, which I don't think it's the best way, and I should properly end the program ending background processes like Chromedriver.

  2. I thought of having a GUI which runs somehow asynchronously and I can have buttons for pausing, and terminating the script. But I am not exactly sure how to approach it, or if this is a good idea to even try. Any suggestion is welcomed.

  3. Use a script monitoring/workflow monitoring framework like AirBnB's Airflow or Luigi. I had only done brief research on this.

A related question but I don't need to return exactly where it's left off

I usually use try and except to do this

while True:
    try:
        Do_Task1()
        Do_Task2()
    except KeyBoardInterrrupt:
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM