How to terminate a python program instantly through keyboard input while the system is busy doing task away from the terminal

I am building an automation using python that requires tab switching, mouse clicking, etc which engages my system completely. During which I cannot access my terminal or taskbar to manually close/stop my program from running.

While the automation is running and something went wrong it is difficult to switch to terminal and press CTRL + C to stop executing since it collapses with the automation making it more of a mess.

I tries using pynput’s keyboard library since I am using it for my automation, but I can’t find a way to run both the scripts to run simultaneously.

Please help me how to stop my application without disturbing its flow through keyboard input like esc key, something like multithreading or any other way I can work with it, thank you.

import json
import automated as auto

# Read the data from the JSON file
with open('mouse.json', 'r') as f:
  data = json.load(f)

# Convert lists back to tuples
account_location = [tuple(lst) for lst in data["account_location"]]
tab_location = [tuple(lst) for lst in data["tab_location"]]

auto.open_ms()
auto.full_screen()
auto.scroll_down()
auto.open_all_accounts(account_location)

for i in range(2): # 2 times for 8 accounts ( 4 accounts per time )
  auto.position_tabs()
  count = 0
  auto.search_tabs(count, tab_location)
  auto.exit_tabs()

auto.shutdown()

NOTE : I do not consider pasting the automated.py file since it’s just a bunch of loops and keyboard input in it. Just to be sure this code is not in loop.

A way/method to stop a python program from executing anytime without engaging with terminal.

You can solve this issue by using a combination of multithreading and a keyboard listener that will allow you to stop the script at any point without interfering with the automation flow. You can use pynput library for keyboard monitoring in a separate thread, and stopping the main automation when a specific key(like ESC) is pressed.

Here’s the code.

  • First, you need to install pynput
pip install pynput
  • Modify your code to include multithreading and a keyboard listener.
import json
import automated as auto
from pynput import keyboard
import threading
import sys

# Flag to control stopping the automation
stop_flag = False

def on_press(key):
    global stop_flag
    try:
        # If ESC is pressed, set the flag to True to stop the automation
        if key == keyboard.Key.esc:
            print("ESC pressed. Stopping automation...")
            stop_flag = True
            
            return False  # Stop the listener
    except Exception as e:
        print(f"Error in listener: {e}")

def run_automation():
    global stop_flag
    # Read the data from the JSON file
    with open('mouse.json', 'r') as f:
        data = json.load(f)

    # Convert lists back to tuples
    account_location = [tuple(lst) for lst in data["account_location"]]
    tab_location = [tuple(lst) for lst in data["tab_location"]]

    auto.open_ms()
    auto.full_screen()
    auto.scroll_down()
    auto.open_all_accounts(account_location)

    for i in range(2):  # 2 times for 8 accounts ( 4 accounts per time )
        if stop_flag:  # Check if stop is requested
            print("Automation stopped.")
            return
        auto.position_tabs()
        count = 0
        auto.search_tabs(count, tab_location)
        auto.exit_tabs()

    auto.shutdown()

# Run the automation in a separate thread
automation_thread = threading.Thread(target=run_automation)
automation_thread.start()

# Start keyboard listener in the main thread
with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

# Join automation thread after listener is done
automation_thread.join()

I hope this will help you a little.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật