File: README.rst

package info (click to toggle)
python-gphoto2 2.6.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,628 kB
  • sloc: ansic: 75,135; python: 4,263; makefile: 4
file content (396 lines) | stat: -rw-r--r-- 17,156 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
python-gphoto2 v\ 2.6.3
=======================

python-gphoto2 is a comprehensive Python interface (or binding) to libgphoto2_.
It is built using SWIG_ to automatically generate the interface code.
This gives direct access to nearly all the libgphoto2 functions_, but sometimes in a rather un-Pythonic manner.

Other Python bindings to libgphoto2_ are available:
piggyphoto_ uses ctypes_ (included in standard Python installations) to interface to the library.
The gphoto2 source tree includes some `Python bindings`_ which also use ctypes_.
`gphoto2-cffi`_ uses cffi_.

.. contents::
   :backlinks: top

Installation
------------

Since python-gphoto2 version 2.3.1 "binary wheels" are provided for many Linux and MacOS computers.
These include a recent version of the libgphoto2_ libraries, and pre-built Python interface modules, which makes installation quick and easy.
Use pip_'s ``--only-binary`` option 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 you *must* install some dependencies before installing python-gphoto2.
See `<INSTALL.rst>`_ for more details.

Raspberry Pi
^^^^^^^^^^^^

Binary wheels for the Raspberry Pi are available from piwheels_.
You need to install some system packages to use these::

    $ sudo apt install libexif12 libgphoto2-6 libgphoto2-port12 libltdl7
    $ pip3 install gphoto2 --user --only-binary :all:

Using python-gphoto2
--------------------

The Python interface to libgphoto2_ should 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" interface
^^^^^^^^^^^^^

These functions are as similar as possible to their libgphoto2_ equivalents.
Most of them return an error code which you must check.

Using SWIG_ to generate the Python interfaces automatically means that every function in libgphoto2_ *should* be available to Python.
You can show the documentation of a function with the ``pydoc`` command (or ``python -m pydoc`` if 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_files

The first part of this text is the function signature and parameter list generated by SWIG.
(Note that ``context`` is 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 online `API documentation`_ shows how it is intended to look.)
Note that this includes a ``list`` parameter 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 of ``gp_camera_folder_list_files`` returns a sequence containing the integer error code and the ``list`` value.

Most of the libgphoto2_ functions 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 persuade SWIG_ to include this extra return value in the documentation.
You should use ``pydoc`` to check the actual parameters expected by the Python function.)

For example, the C code:

.. code:: c

    #include "gphoto2.h"
    int error;
    Camera *camera;
    error = gp_camera_new(&camera);
    ...
    error = gp_camera_unref(camera);

has this Python equivalent:

.. code:: python

    import gphoto2 as gp
    error, 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):

.. code:: python

    import gphoto2 as gp
    error, 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" interface
^^^^^^^^^^^^^^^^^^^^^^^^^^^

This is the preferred way to use libgphoto2_ from Python.
Most of the libgphoto2_ functions 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 by ``camera.init()``.
These methods also include error checking.
If an error occurs they raise a Python ``GPhoto2Error`` exception.

The example program can be re-written as follows:

.. code:: python

    import gphoto2 as gp
    camera = gp.Camera()
    camera.init()
    text = camera.get_summary()
    print('Summary')
    print('=======')
    print(str(text))
    camera.exit()

No additional error checking is required.

Error checking
^^^^^^^^^^^^^^

Most of the libgphoto2_ functions return an integer to indicate success or failure.
The Python interface includes a ``check_result()`` function to check these values and raise a ``GPhoto2Error`` exception if an error occurs.

This function also removes the error code from lists such as that returned by ``gp_camera_new()`` in the example.
Using this function the earlier example becomes:

.. code:: python

    import gphoto2 as gp
    camera = 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 the ``check_result()`` function by adjusting the ``error_severity`` variable:

.. code:: python

    import gphoto2 as gp
    gp.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 a ``GP_ERROR`` error occurs.
However, this is a "blanket" approach that treats all ``GP_ERROR`` errors the same.
It is better to test for particular error conditions after particular operations, as described below.

The ``GPhoto2Error`` exception object has two attributes that may be useful in an exception handler.
``GPhoto2Error.code`` stores the integer error generated by the library function and ``GPhoto2Error.string`` stores the corresponding error message.

For example, to wait for a user to connect a camera you could do something like this:

.. code:: python

    import gphoto2 as gp
    ...
    print('Please connect and switch on your camera')
    while True:
        try:
            camera.init()
        except gp.GPhoto2Error as ex:
            if ex.code == gp.GP_ERROR_MODEL_NOT_FOUND:
                # no camera, try again in 2 seconds
                time.sleep(2)
                continue
            # some other error we can't handle here
            raise
        # operation completed successfully so exit loop
        break
    # 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:

.. code:: python

    import gphoto2 as gp
    ...
    print('Please connect and switch on your camera')
    while True:
        error = gp.gp_camera_init(camera)
        if error >= gp.GP_OK:
            # operation completed successfully so exit loop
            break
        if error != gp.GP_ERROR_MODEL_NOT_FOUND:
            # some other error we can't handle here
            raise gp.GPhoto2Error(error)
        # no camera, try again in 2 seconds
        time.sleep(2)
    # continue with rest of program
    ...

Logging
^^^^^^^

The libgphoto2_ library includes functions (such as ``gp_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 using libgphoto2_ from Python.
The Python interface includes a ``use_python_logging()`` function to connect libgphoto2_ logging to the standard Python logging system.
If you want to see the messages you should call ``use_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 (libgphoto2_ is rather verbose) so this could be controlled by a "verbose" or "debug" option in your application.

The libgphoto2_ logging 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 to ``use_python_logging()``:

.. code:: python

    import logging
    import gphoto2 as gp
    ...
    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``, ``string`` and an optional ``data``.
The ``data`` parameter 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 with ``gp_log_add_func``:

.. code:: python

    import gphoto2 as gp
    ...
    def callback(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 functions
--------------------

Some 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 ``-Wd`` flag 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 problem
--------------------------------

If 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 email jim@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 the `gphoto2 command line program`_.
If the problem persists then it might be worth asking on the `gphoto-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 functions
-------------------------------

gp_camera_capture_preview / gp_camera_file_get
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Before python-gphoto2 version 2.5.0 these functions (and their corresponding "object oriented" methods) always allocated and returned a new ``CameraFile`` object.
Now you can pass in a previously allocated ``CameraFile`` for them to use, but this is deprecated.
In this case it is not returned by the function.

If you need to use a ``Context`` value with these functions without passing in a ``CameraFile``, then pass ``None`` in place of the ``CameraFile`` object.
In a future release the ``CameraFile`` parameter will be removed.

gp_log_add_func / use_python_logging
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Since 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 to ``gp_log_remove_func`` to 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 the ``context_with_callbacks.py`` example for a convenient way to do this.

gp_file_get_data_and_size / CameraFile.get_data_and_size
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Since python-gphoto2 version 2.4.0 these functions return a Python memoryview_ object.
Prior to that they returned a ``FileData`` object that supports the `buffer protocol`_ so its data can be made accessible to Python by using a memoryview_ object.
This allows the data to be used without copying.
See the ``copy-data.py`` example for typical usage.

Note that if the CameraFile object is deleted, or another function (such as ``gp_file_set_data_and_size`` or ``gp_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_size
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Since python-gphoto2 version 2.1.0 these functions accept any `bytes-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_read
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The ``buf`` parameter 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 the ``copy-chunks.py`` example which uses memoryview_ to expose a bytearray_.

gp_camera_wait_for_event / Camera.wait_for_event
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

These functions return both the event type and the event data.
The data you get depends on the type.
``GP_EVENT_FILE_ADDED`` and ``GP_EVENT_FOLDER_ADDED`` events return a ``CameraFilePath``, others return ``None`` or a text string.

Licence
-------

| python-gphoto2 - Python interface to libgphoto2
| http://github.com/jim-easterbrook/python-gphoto2
| Copyright (C) 2014-23  Jim Easterbrook  jim@jim-easterbrook.me.uk

python-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/>.

.. _API documentation: http://www.gphoto.org/doc/api/
.. _buffer protocol:   https://docs.python.org/3/c-api/buffer.html
.. _bytearray:         https://docs.python.org/3/library/functions.html#bytearray
.. _bytes-like object: https://docs.python.org/3/glossary.html#term-bytes-like-object
.. _cffi:              http://cffi.readthedocs.org/
.. _ctypes:            https://docs.python.org/3/library/ctypes.html
.. _functions:         http://www.gphoto.org/doc/api/
.. _GitHub:            https://github.com/jim-easterbrook/python-gphoto2
.. _gphoto2-cffi:      https://github.com/jbaiter/gphoto2-cffi
.. _gphoto2 command line program:
                       http://gphoto.org/doc/manual/using-gphoto2.html
.. _gphoto-user mailing list:
                       http://gphoto.org/mailinglists/
.. _libgphoto2:        http://www.gphoto.org/proj/libgphoto2/
.. _memoryview:        https://docs.python.org/3/library/stdtypes.html#memoryview
.. _Python bindings:
   http://sourceforge.net/p/gphoto/code/HEAD/tree/trunk/bindings/libgphoto2-python/
.. _piggyphoto:        https://github.com/alexdu/piggyphoto
.. _pip:               https://pip.pypa.io/
.. _piwheels:          https://www.piwheels.org/project/gphoto2/
.. _SWIG:              http://swig.org/