Package: gphoto2
python-gphoto2 is a comprehensive Python interface (or binding) tolibgphoto2.
It is built usingSWIGto automatically generate the interface code.
This gives direct access to nearly all the libgphoto2functions, but sometimes in a rather un-Pythonic manner.Other Python bindings tolibgphoto2are available:piggyphotousesctypes(included in standard Python installations) to interface to the library.
The gphoto2 source tree includes somePython bindingswhich also usectypes.gphoto2-cffiusescffi.ContentsInstallationRaspberry PiUsing python-gphoto2“C” interface“Object oriented” interfaceError checkingLoggingDeprecated functionsWhat to do if you have a problemNotes on some gphoto2 functionsgp_log_add_func / use_python_logginggp_context_set_idle_func / gp_context_set_progress_funcs / etc.gp_file_get_data_and_size / CameraFile.get_data_and_sizegp_file_set_data_and_size / CameraFile.set_data_and_sizegp_camera_file_read / Camera.file_readgp_camera_wait_for_event / Camera.wait_for_eventLicenceInstallationSince python-gphoto2 version 2.3.1 “binary wheels” are provided for many Linux and MacOS computers.
These include a recent version of thelibgphoto2libraries, and pre-built Python interface modules, which makes installation quick and easy.
Usepip’s--only-binaryoption to install one of these wheels:$ pip3 install gphoto2 --user --only-binary :all:If this fails it is most likely because none of the available wheels is compatible with your computer.
In this case youmustinstall some dependencies before installing python-gphoto2.
SeeINSTALL.rstfor more details.Raspberry PiBinary wheels for the Raspberry Pi are available frompiwheels.
You need to install some system packages to use these:$ sudo apt install libexif12 libgphoto2-6 libgphoto2-port12 libltdl7
$ pip3 install gphoto2 --userUsing python-gphoto2The Python interface tolibgphoto2should allow you to do anything you could do in a C program.
However, there are still bits missing and functions that cannot be called from Python.
Let me know if you run into any problems.The following paragraphs show how the Python interfaces differ from C.
See the example programs for typical usage of the Python gphoto2 API.“C” interfaceThese functions are as similar as possible to theirlibgphoto2equivalents.
Most of them return an error code which you must check.UsingSWIGto generate the Python interfaces automatically means that every function inlibgphoto2shouldbe available to Python.
You can show the documentation of a function with thepydoccommand (orpython-mpydocif you installed gphoto2 with pip inside a virtual environment):$ pydoc3 gphoto2.gp_camera_folder_list_files
Help on built-in function gp_camera_folder_list_files in gphoto2:

gphoto2.gp_camera_folder_list_files = gp_camera_folder_list_files(...)
    gp_camera_folder_list_files(camera, folder, context) -> int

    Parameters
    ----------
    camera: gphoto2.Camera
    folder: str
    context: gphoto2.Context (default=None)


    Lists the files in supplied `folder`.

    Parameters
    ----------
    * `camera` :
        a Camera
    * `folder` :
        a folder
    * `list` :
        a CameraList
    * `context` :
        a GPContext

    Returns
    -------
    a gphoto2 error code

    See also gphoto2.Camera.folder_list_filesThe first part of this text is the function signature and parameter list generated by SWIG.
(Note thatcontextis optional - it’s only needed if you need the callback functions that can be  associated with a context.)
The rest of the text is copied from the “doxygen” format documentation in the C source code.
(The onlineAPI documentationshows how it is intended to look.)
Note that this includes alistparameter that is not in the function signature.
In C this is an “output” parameter, a concept that doesn’t really exist in Python.
The Python version ofgp_camera_folder_list_filesreturns a sequence containing the integer error code and thelistvalue.Most of thelibgphoto2functions that use pointer parameters to return values in the C API have been adapted like this in the Python API.
(Unfortunately I’ve not found a way to persuadeSWIGto include this extra return value in the documentation.
You should usepydocto check the actual parameters expected by the Python function.)For example, the C code:#include"gphoto2.h"interror;Camera*camera;error=gp_camera_new(&camera);...error=gp_camera_unref(camera);has this Python equivalent:importgphoto2asgperror,camera=gp.gp_camera_new()...Note that the gp_camera_unref() call is not needed.
It is called automatically when the Python camera object is deleted.Here is a complete example program (without any error checking):importgphoto2asgperror,camera=gp.gp_camera_new()error=gp.gp_camera_init(camera)error,text=gp.gp_camera_get_summary(camera)print('Summary')print('=======')print(text.text)error=gp.gp_camera_exit(camera)“Object oriented” interfaceThis is the preferred way to uselibgphoto2from Python.
Most of thelibgphoto2functions have been added as methods of the appropriate GPhoto2 object.
This allows GPhoto2 to be used in a more “Pythonic” style.
For example,gp.gp_camera_init(camera)can be replaced bycamera.init().
These methods also include error checking.
If an error occurs they raise a PythonGPhoto2Errorexception.The example program can be re-written as follows:importgphoto2asgpcamera=gp.Camera()camera.init()text=camera.get_summary()print('Summary')print('=======')print(str(text))camera.exit()No additional error checking is required.Error checkingMost of thelibgphoto2functions return an integer to indicate success or failure.
The Python interface includes acheck_result()function to check these values and raise aGPhoto2Errorexception if an error occurs.This function also removes the error code from lists such as that returned bygp_camera_new()in the example.
Using this function the earlier example becomes:importgphoto2asgpcamera=gp.check_result(gp.gp_camera_new())gp.check_result(gp.gp_camera_init(camera))text=gp.check_result(gp.gp_camera_get_summary(camera))print('Summary')print('=======')print(text.text)gp.check_result(gp.gp_camera_exit(camera))There may be some circumstances where you don’t want an exception to be raised when some errors occur.
You can “fine tune” the behaviour of thecheck_result()function by adjusting theerror_severityvariable:importgphoto2asgpgp.error_severity[gp.GP_ERROR]=logging.WARNING...In this case a warning message will be logged (using Python’s standard logging module) but no exception will be raised when aGP_ERRORerror occurs.
However, this is a “blanket” approach that treats allGP_ERRORerrors the same.
It is better to test for particular error conditions after particular operations, as described below.TheGPhoto2Errorexception object has two attributes that may be useful in an exception handler.GPhoto2Error.codestores the integer error generated by the library function andGPhoto2Error.stringstores the corresponding error message.For example, to wait for a user to connect a camera you could do something like this:importgphoto2asgp...print('Please connect and switch on your camera')whileTrue:try:camera.init()exceptgp.GPhoto2Errorasex:ifex.code==gp.GP_ERROR_MODEL_NOT_FOUND:# no camera, try again in 2 secondstime.sleep(2)continue# some other error we can't handle hereraise# operation completed successfully so exit loopbreak# continue with rest of program...When just calling a single function like this, it’s probably easier to test the error value directly instead of using Python exceptions:importgphoto2asgp...print('Please connect and switch on your camera')whileTrue:error=gp.gp_camera_init(camera)iferror>=gp.GP_OK:# operation completed successfully so exit loopbreakiferror!=gp.GP_ERROR_MODEL_NOT_FOUND:# some other error we can't handle hereraisegp.GPhoto2Error(error)# no camera, try again in 2 secondstime.sleep(2)# continue with rest of program...LoggingThelibgphoto2library includes functions (such asgp_log()) to output messages from its various functions.
These messages are mostly used for debugging purposes, and it can be helpful to see them when usinglibgphoto2from Python.
The Python interface includes ause_python_logging()function to connectlibgphoto2logging to the standard Python logging system.
If you want to see the messages you should calluse_python_logging()near the start of your program, as shown in the examples.
In normal use you probably don’t want to see these messages (libgphoto2is rather verbose) so this could be controlled by a “verbose” or “debug” option in your application.Thelibgphoto2logging messages have four possible severity levels, each of which is mapped to a suitable Python logging severity.
You can override this mapping by passing your own touse_python_logging():importloggingimportgphoto2asgp...callback_obj=gp.check_result(gp.use_python_logging(mapping={gp.GP_LOG_ERROR:logging.INFO,gp.GP_LOG_DEBUG:logging.DEBUG,gp.GP_LOG_VERBOSE:logging.DEBUG-3,gp.GP_LOG_DATA:logging.DEBUG-6}))...If you prefer to use your own logging system you can define a logging callback function in Python.
The function must take 3 or 4 parameters:level,domain,stringand an optionaldata.
Thedataparameter allows you to pass some user data to your callback function (e.g. to log which thread an error occurred in):
The callback function is installed withgp_log_add_func:importgphoto2asgp...defcallback(level,domain,string,data=None):print('Callback: level =',level,', domain =',domain,', string =',string,'data =',data)...callback_obj1=gp.check_result(gp.gp_log_add_func(gp.GP_LOG_VERBOSE,callback))callback_obj2=gp.check_result(gp.gp_log_add_func(gp.GP_LOG_VERBOSE,callback,123))...Deprecated functionsSome functions are intended for use by camera drivers and should not have been included in the Python interface.
They will be removed in a future release.
During testing you should run your software with Python’s-Wdflag to show the warnings issued if you use any of the deprecated functions.
Please contact me if you have reason to believe a deprecated function should not be removed.What to do if you have a problemIf you find a problem in the Python gphoto2 interface (e.g. a segfault, a missing function, or a function without a usable return value) then please report it on the GitHub “issues” page (https://github.com/jim-easterbrook/python-gphoto2/issues) or emailjim@jim-easterbrook.me.uk.If your problem is more general, e.g. difficulty with capturing multiple images, then try doing what you want to do with thegphoto2 command line program.
If the problem persists then it might be worth asking on thegphoto-user mailing list.
Another reader of the mailing list may have the same camera model and already know what to do.Notes on some gphoto2 functionsgp_log_add_func / use_python_loggingSince python-gphoto2 version 2.0.0 these functions return a sequence containing an error code and an object storing details of the callback.
The callback is automatically uninstalled when this object is deleted.In earlier versions of python-gphoto2 these functions return an integer id that must be passed togp_log_remove_functo uninstall the callback.gp_context_set_idle_func / gp_context_set_progress_funcs / etc.These functions are only usable since python-gphoto2 version 1.9.0.
They return a Python object which your program must store until the callback(s) are no longer required.
Deleting the returned object cancels the callback(s), so there is no need to do this yourself.
See thecontext_with_callbacks.pyexample for a convenient way to do this.gp_file_get_data_and_size / CameraFile.get_data_and_sizeSince python-gphoto2 version 2.4.0 these functions return a Pythonmemoryviewobject.
Prior to that they returned aFileDataobject that supports thebuffer protocolso its data can be made accessible to Python by using amemoryviewobject.
This allows the data to be used without copying.
See thecopy-data.pyexample for typical usage.Note that if the CameraFile object is deleted, or another function (such asgp_file_set_data_and_sizeorgp_file_open) changes the CameraFile’s data, then this object will be invalidated and you will probably get a segmentation fault.gp_file_set_data_and_size / CameraFile.set_data_and_sizeSince python-gphoto2 version 2.1.0 these functions accept anybytes-like object.
In earlier versions of python-gphoto2 these functions required a string and its length, and didn’t work correctly anyway.gp_camera_file_read / Camera.file_readThebufparameter can be any Python object that exposes a writeable buffer interface.
This allows you to read a file directly into a Python object without additional copying.
See thecopy-chunks.pyexample which usesmemoryviewto expose abytearray.gp_camera_wait_for_event / Camera.wait_for_eventThese functions return both the event type and the event data.
The data you get depends on the type.GP_EVENT_FILE_ADDEDandGP_EVENT_FOLDER_ADDEDevents return aCameraFilePath, others returnNoneor a text string.Licencepython-gphoto2 - Python interface to libgphoto2http://github.com/jim-easterbrook/python-gphoto2Copyright (C) 2014-23  Jim Easterbrookjim@jim-easterbrook.me.ukpython-gphoto2 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.python-gphoto2 is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.You should have received a copy of the GNU Lesser General Public
License along with python-gphoto2.  If not, see
<https://www.gnu.org/licenses/>.