You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现脚本等待15秒无输入则终止,有输入则执行umcn()函数

Solution for Timeout Input Check in Your Script

Got it, let's fix this up for you! The issue with your current code is that time.sleep(15) blocks the script entirely—users can't type anything during those 15 seconds, so you can't check for input in real time. Here's how to implement the "wait 15 seconds for input, terminate if none" behavior properly:

Working Implementation (Unix/Linux/macOS)

We'll use the signal module to set a 15-second timer. If no input is received before the timer triggers, the script terminates. If input is entered, we cancel the timer and run your umcn() function.

import signal
import os

def umcn():
    # Replace this with your actual umcn() function logic
    print("Executing umcn() with your new input!")

def timeout_handler(signum, frame):
    print("\nNo input received—terminating script.")
    os._exit(1)

# Set up the 15-second timeout signal
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(15)

print("Enter a new number: ")
try:
    user_input = input()
    # Cancel the timeout since we got input
    signal.alarm(0)
    umcn()
except KeyboardInterrupt:
    # Handle Ctrl+C gracefully if needed
    print("\nScript interrupted by user.")
    os._exit(1)

For Windows Users

The signal.alarm() method doesn't work on Windows. Instead, use the threading module to create a separate timeout thread:

import threading
import os

def umcn():
    # Replace this with your actual umcn() function logic
    print("Executing umcn() with your new input!")

def terminate_on_timeout():
    print("\nNo input received—terminating script.")
    os._exit(1)

# Start a timer thread that triggers termination after 15 seconds
timeout_timer = threading.Timer(15, terminate_on_timeout)
timeout_timer.start()

print("Enter a new number: ")
try:
    user_input = input()
    # Cancel the timer if input is received
    timeout_timer.cancel()
    umcn()
except:
    # Catch any exceptions that occur if the script terminates mid-input
    pass

Key Explanations

  • Why your original code failed: time.sleep(15) pauses the script completely—users can't interact with the input prompt until the sleep finishes, which defeats the timeout purpose.
  • Using os._exit(1): This is ideal here because it terminates the script immediately without unnecessary cleanup, which is exactly what you want for a forced timeout.
  • Input handling: The input() call will block until the user enters text, but our timer ensures it won't wait indefinitely.

内容的提问来源于stack exchange,提问作者Nikola Pavlovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:32:13