I'm pretty new to both Python and utilizing the GPIO pins on my Raspberry Pi. I am trying to make a "trail camera" that will take pictures of birds when they land on the branches of the trees just off of my back porch.

I have a PIR motion sensor and the camera module hooked up. I have written the following script, largely copied from here, to have the motion sensor wait for motion, then take a photograph, then reset to waiting for the next bit of motion.

import picamera
from datetime import datetime
from time import sleep
from gpiozero import MotionSensor

pir = MotionSensor(17)

def generate_filename():
    timestampe = datetime.strftime(datetime.now(), "%Y-%m-%d-%H-%M-%S-%f")
    filename = 'home/pi/trail_cam_photos/photo_%s' % timestamp
    return filename

while True:
    while pir.motion_detected:
        with picamera.PiCamera as camera:
            camera.resolution=(1024, 768)
            file = generate_filename

When I run the script and then wave my hand over the PIR sensor, I get the following error:

Traceback (most recent call last):
  File "trail_cam.py", line 19, in <module>
    with picamera.PiCamera as camera:
AttributeError: __exit__

What can cause this error?

1 Answer 1


The error:

AttributeError: __exit__

indicates that the object is not a context manager. In this particular case it is because picamera.PiCamera is a class not an instance of a class. The proper usage to use this class as a context manager would be:

with picamera.PiCamera() as camera:

Note the addition of the (). This instantiates a PiCamera and then the context manager should work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.