Skip to content

Instantly share code, notes, and snippets.

@timsavage
Created September 10, 2021 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timsavage/90dd86801974e06444aadcdce5dde359 to your computer and use it in GitHub Desktop.
Save timsavage/90dd86801974e06444aadcdce5dde359 to your computer and use it in GitHub Desktop.
Python script to monitor when a webcamera is activated on Linux
import shutil
import subprocess
import time
COMMANDS = [shutil.which("lsmod")]
MOD_NAME = b"uvcvideo"
def get_uvc_user_count() -> int:
"""
Obtain the number of users of the UVC Video module
"""
result = subprocess.check_output(COMMANDS)
for line in result.splitlines():
cols = line.split()
if cols[0] == MOD_NAME:
return int(cols[2])
def on_air():
"""
Camera is in use
"""
print("On Air!")
def off_air():
"""
Camera is no longer in user
"""
print("Off Air!")
def monitor_camera(check_frequency: float = 1):
"""
Monitor state of camera
"""
is_active = False
while True:
user_count = get_uvc_user_count()
if user_count > 0:
if not is_active:
is_active = True
on_air()
else:
if is_active:
is_active = False
off_air()
time.sleep(check_frequency)
def main():
monitor_camera()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment