Open ghost opened 3 years ago
Pycaw uses the comtypes library for using COM.
For the communication with windows its necessary to comtypes.CoInitialize()
(at the start) and comtypes.CoUninitialize()
(in the end) in every thread.
(If you want more information look at COM Apartment threaded.)
If you use pycaw in the main thread of your script CoInitialize() will be called on import of the module and CoUninitialize() on close.
But when you are using multiple threads in your python script (indirectly for example by using the library keyboard) then you must tell the thread to comtypes.CoInitialize() and to comtypes.CoUninitialize()
Following is stated in the comtypes.__init__.py
# COM is initialized automatically for the thread that imports this
# module for the first time. [...]
#
# A shutdown function is registered with atexit, so that
# CoUninitialize is called when Python is shut down.
# We need to have CoUninitialize for multithreaded model where we have
# to initialize and uninitialize COM for every new thread (except main)
# in which we are using COM
so implementing that would look the following (and it works too ;) )
from pycaw.pycaw import AudioUtilities
from comtypes import CoInitialize, CoUninitialize
import keyboard
import time
def audio_stuff():
CoInitialize()
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
if session.Process:
print(str(session))
CoUninitialize()
keyboard.add_hotkey('4', audio_stuff)
time.sleep(3600*24*30)
Hello! I try to use pycaw with keyboard package. https://github.com/boppreh/keyboard
If you run this code and press "4" then error occurs.