社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python3中是否有任何命令/模块可以帮助运行一个函数x秒,然后移到程序的另一部分?

sammy7 • 4 年前 • 285 次点击  

我只想运行一个函数x秒,如果在x秒内用户输入任何键,那么程序应该终止,否则它应该继续运行下去。

# Python Program - Shutdown Computer

import os
import time

check = int(input("enter the seconds"))

for i in range ( 10,0):
 print(i)
#  time.sleep(1)

 while i<check :
  c=input("enter any key to stop")
  if c
  exit();

os.system("shutdown /s /t 1")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38383
 
285 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Fab
Reply   •   1 楼
Fab    4 年前

也许考虑一个线程方法。

此解决方案适用于Windows。

对于Win和Linux,请尝试键盘模块: https://pypi.org/project/keyboard/

import os
import threading
import time
import msvcrt
import queue
import sys

WAIT = 5  # seconds


def keypress(out_q):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        x = msvcrt.kbhit()
        if x:
            ret = ord(msvcrt.getch())
            out_q.put(ret)


q = queue.Queue()
key = threading.Thread(name="wait for keypress", target=keypress, args=(q,))
key.start()
print("waiting", WAIT, "seconds before shutdown - to abort hit <SPACE>.")
start_time = time.time()
now = time.time()
data = ""
counter = 0
sys.stdout.write(str(WAIT) + "... ")
while now - start_time < WAIT and not data == 32:  # 32 = space bar
    now = time.time()
    try:
        data = q.get(False)
    except queue.Empty:
        pass
    if now - start_time > counter + 1:
        counter += 1
        sys.stdout.write(str(WAIT - counter) + "... ")

    sys.stdout.flush()

key.do_run = False
key.join()

if data == 32:
    print("\n\nok. exiting...")
    exit()

print("\n\nUser did NOT abort - code continues here...")
# Do whatever