Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

background process - How to keep a python script idle without using too many ressources

Basically the title, i have a small python script (python 3.9, Windows 10) that i would like to keep running in the background. It is currently listening for keyboard hotkeys and acting like a macro engine. I want it to stay idle, since i use the keyboard module so i doesnt need to call anything, just wait.
I tried a while loop with either pass or sleep in it, but both have downsides, the one with pass using a lot of cpu ressources, and the one with sleep being very unreliable.

Is there any pretty/good practice way of doing this ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest to use some library that does the trick for you.

For example you can try Asyncio:

import asyncio 

loop = asyncio.get_event_loop()
try:
    loop.run_forever()
finally:
    loop.close()

Here's an Asyncio example for keypress.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...