0

I'm hoping that you can look at my code and tell me how I'm not using threading correctly. I'm trying to send commands to my usb attached camera via Python's threading module. "get_live_view" tells the camera to take a low resolution image every 2 seconds. "Listener" is waiting for the character 'c' to tell "capture_image" to take a high resolution image. I tried to use threading so both functions would not simultaneously access the camera, but whenever I press 'c', I get the error message: "Could not claim the USB device... Make sure no other program or kernel module is using the device."

import os, threading
from time import sleep
from pynput.keyboard import Key, Listener

def capture_image():
    os.system("gphoto2 --capture-image-and-download --no-keep")
    os.system("rm capt0000.jpg")
    sleep(1)

def on_press(key):
    if key.char in ('c'):
        print('capture')
        t2 = threading.Thread(target=capture_image, args=())
        t2.start(); t2.join()

def on_release(key):
    if key == Key.esc:
        # Stop listener
        return False

def capture_preview():
    os.system("gphoto2 --capture-preview")
    os.system("rm capture_preview.jpg")
    sleep(2)

def get_live_view():
    while True:
        t3=threading.Thread(target=capture_preview, args=())
        t3.start(), t3.join()

t1 = threading.Thread(target=get_live_view, args=())
t1.start()

with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()
user1106278
  • 747
  • 1
  • 9
  • 18
  • Try using a semaphore to guard the device. – Marichyasana Nov 11 '19 at 20:10
  • @Marichyasana: Thanks for the advice. I added "sem = threading.Semaphore()" and sem.acquire() / sem.release() around the calls to camera and I got the same error message immediately without taking any photos. – user1106278 Nov 12 '19 at 17:34

0 Answers0