INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add a vod, with one input. @param p_instance: the instance. @param psz_name: the name of the new vod media. @param psz_input: the input MRL. @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new vod. @param psz_mux: the muxer of the vod media. @return: 0 on success, -1 on error.
def libvlc_vlm_add_vod(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux): '''Add a vod, with one input. @param p_instance: the instance. @param psz_name: the name of the new vod media. @param psz_input: the input MRL. @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new vod. @param psz_mux: the muxer of the vod media. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_add_vod', None) or \ _Cfunction('libvlc_vlm_add_vod', ((1,), (1,), (1,), (1,), (1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_char_p) return f(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux)
Delete a media (VOD or broadcast). @param p_instance: the instance. @param psz_name: the media to delete. @return: 0 on success, -1 on error.
def libvlc_vlm_del_media(p_instance, psz_name): '''Delete a media (VOD or broadcast). @param p_instance: the instance. @param psz_name: the media to delete. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_del_media', None) or \ _Cfunction('libvlc_vlm_del_media', ((1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p) return f(p_instance, psz_name)
Enable or disable a media (VOD or broadcast). @param p_instance: the instance. @param psz_name: the media to work on. @param b_enabled: the new status. @return: 0 on success, -1 on error.
def libvlc_vlm_set_enabled(p_instance, psz_name, b_enabled): '''Enable or disable a media (VOD or broadcast). @param p_instance: the instance. @param psz_name: the media to work on. @param b_enabled: the new status. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_enabled', None) or \ _Cfunction('libvlc_vlm_set_enabled', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, b_enabled)
Set the output for a media. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error.
def libvlc_vlm_set_output(p_instance, psz_name, psz_output): '''Set the output for a media. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_output', None) or \ _Cfunction('libvlc_vlm_set_output', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_output)
Set a media's input MRL. This will delete all existing inputs and add the specified one. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error.
def libvlc_vlm_set_input(p_instance, psz_name, psz_input): '''Set a media's input MRL. This will delete all existing inputs and add the specified one. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_input', None) or \ _Cfunction('libvlc_vlm_set_input', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_input)
Set a media's loop status. @param p_instance: the instance. @param psz_name: the media to work on. @param b_loop: the new status. @return: 0 on success, -1 on error.
def libvlc_vlm_set_loop(p_instance, psz_name, b_loop): '''Set a media's loop status. @param p_instance: the instance. @param psz_name: the media to work on. @param b_loop: the new status. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_loop', None) or \ _Cfunction('libvlc_vlm_set_loop', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, b_loop)
Set a media's vod muxer. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_mux: the new muxer. @return: 0 on success, -1 on error.
def libvlc_vlm_set_mux(p_instance, psz_name, psz_mux): '''Set a media's vod muxer. @param p_instance: the instance. @param psz_name: the media to work on. @param psz_mux: the new muxer. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_mux', None) or \ _Cfunction('libvlc_vlm_set_mux', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p) return f(p_instance, psz_name, psz_mux)
Seek in the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @param f_percentage: the percentage to seek to. @return: 0 on success, -1 on error.
def libvlc_vlm_seek_media(p_instance, psz_name, f_percentage): '''Seek in the named broadcast. @param p_instance: the instance. @param psz_name: the name of the broadcast. @param f_percentage: the percentage to seek to. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_seek_media', None) or \ _Cfunction('libvlc_vlm_seek_media', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_float) return f(p_instance, psz_name, f_percentage)
Return information about the named media as a JSON string representation. This function is mainly intended for debugging use, if you want programmatic access to the state of a vlm_media_instance_t, please use the corresponding libvlc_vlm_get_media_instance_xxx -functions. Currently there are no such functions available for vlm_media_t though. @param p_instance: the instance. @param psz_name: the name of the media, if the name is an empty string, all media is described. @return: string with information about named media, or NULL on error.
def libvlc_vlm_show_media(p_instance, psz_name): '''Return information about the named media as a JSON string representation. This function is mainly intended for debugging use, if you want programmatic access to the state of a vlm_media_instance_t, please use the corresponding libvlc_vlm_get_media_instance_xxx -functions. Currently there are no such functions available for vlm_media_t though. @param p_instance: the instance. @param psz_name: the name of the media, if the name is an empty string, all media is described. @return: string with information about named media, or NULL on error. ''' f = _Cfunctions.get('libvlc_vlm_show_media', None) or \ _Cfunction('libvlc_vlm_show_media', ((1,), (1,),), string_result, ctypes.c_void_p, Instance, ctypes.c_char_p) return f(p_instance, psz_name)
Get vlm_media instance position by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: position as float or -1. on error.
def libvlc_vlm_get_media_instance_position(p_instance, psz_name, i_instance): '''Get vlm_media instance position by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: position as float or -1. on error. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_position', None) or \ _Cfunction('libvlc_vlm_get_media_instance_position', ((1,), (1,), (1,),), None, ctypes.c_float, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance)
Get vlm_media instance time by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: time as integer or -1 on error.
def libvlc_vlm_get_media_instance_time(p_instance, psz_name, i_instance): '''Get vlm_media instance time by name or instance id. @param p_instance: a libvlc instance. @param psz_name: name of vlm media instance. @param i_instance: instance id. @return: time as integer or -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_get_media_instance_time', None) or \ _Cfunction('libvlc_vlm_get_media_instance_time', ((1,), (1,), (1,),), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int) return f(p_instance, psz_name, i_instance)
Get libvlc_event_manager from a vlm media. The p_event_manager is immutable, so you don't have to hold the lock. @param p_instance: a libvlc instance. @return: libvlc_event_manager.
def libvlc_vlm_get_event_manager(p_instance): '''Get libvlc_event_manager from a vlm media. The p_event_manager is immutable, so you don't have to hold the lock. @param p_instance: a libvlc instance. @return: libvlc_event_manager. ''' f = _Cfunctions.get('libvlc_vlm_get_event_manager', None) or \ _Cfunction('libvlc_vlm_get_event_manager', ((1,),), class_result(EventManager), ctypes.c_void_p, Instance) return f(p_instance)
(INTERNAL) Convert 'i.i.i[.i]' str to int.
def _dot2int(v): '''(INTERNAL) Convert 'i.i.i[.i]' str to int. ''' t = [int(i) for i in v.split('.')] if len(t) == 3: t.append(0) elif len(t) != 4: raise ValueError('"i.i.i[.i]": %r' % (v,)) if min(t) < 0 or max(t) > 255: raise ValueError('[0..255]: %r' % (v,)) i = t.pop(0) while t: i = (i << 8) + t.pop(0) return i
Example callback, useful for debugging.
def debug_callback(event, *args, **kwds): '''Example callback, useful for debugging. ''' l = ['event %s' % (event.type,)] if args: l.extend(map(str, args)) if kwds: l.extend(sorted('%s=%s' % t for t in kwds.items())) print('Debug callback (%s)' % ', '.join(l))
Register an event notification. @param eventtype: the desired event type to be notified about. @param callback: the function to call when the event occurs. @param args: optional positional arguments for the callback. @param kwds: optional keyword arguments for the callback. @return: 0 on success, ENOMEM on error. @note: The callback function must have at least one argument, an Event instance. Any other, optional positional and keyword arguments are in B{addition} to the first one.
def event_attach(self, eventtype, callback, *args, **kwds): """Register an event notification. @param eventtype: the desired event type to be notified about. @param callback: the function to call when the event occurs. @param args: optional positional arguments for the callback. @param kwds: optional keyword arguments for the callback. @return: 0 on success, ENOMEM on error. @note: The callback function must have at least one argument, an Event instance. Any other, optional positional and keyword arguments are in B{addition} to the first one. """ if not isinstance(eventtype, EventType): raise VLCException("%s required: %r" % ('EventType', eventtype)) if not hasattr(callback, '__call__'): # callable() raise VLCException("%s required: %r" % ('callable', callback)) # check that the callback expects arguments if not any(getargspec(callback)[:2]): # list(...) raise VLCException("%s required: %r" % ('argument', callback)) if self._callback_handler is None: _called_from_ctypes = ctypes.CFUNCTYPE(None, ctypes.POINTER(Event), ctypes.c_void_p) @_called_from_ctypes def _callback_handler(event, k): """(INTERNAL) handle callback call from ctypes. @note: We cannot simply make this an EventManager method since ctypes does not prepend self as the first parameter, hence this closure. """ try: # retrieve Python callback and arguments call, args, kwds = self._callbacks[k] # deref event.contents to simplify callback code call(event.contents, *args, **kwds) except KeyError: # detached? pass self._callback_handler = _callback_handler self._callbacks = {} k = eventtype.value r = libvlc_event_attach(self, k, self._callback_handler, k) if not r: self._callbacks[k] = (callback, args, kwds) return r
Unregister an event notification. @param eventtype: the event type notification to be removed.
def event_detach(self, eventtype): """Unregister an event notification. @param eventtype: the event type notification to be removed. """ if not isinstance(eventtype, EventType): raise VLCException("%s required: %r" % ('EventType', eventtype)) k = eventtype.value if k in self._callbacks: del self._callbacks[k] # remove, regardless of libvlc return value libvlc_event_detach(self, k, self._callback_handler, k)
Create a new MediaPlayer instance. @param uri: an optional URI to play in the player.
def media_player_new(self, uri=None): """Create a new MediaPlayer instance. @param uri: an optional URI to play in the player. """ p = libvlc_media_player_new(self) if uri: p.set_media(self.media_new(uri)) p._instance = self return p
Create a new Media instance. If mrl contains a colon (:) preceded by more than 1 letter, it will be treated as a URL. Else, it will be considered as a local path. If you need more control, directly use media_new_location/media_new_path methods. Options can be specified as supplementary string parameters, but note that many options cannot be set at the media level, and rather at the Instance level. For instance, the marquee filter must be specified when creating the vlc.Instance or vlc.MediaPlayer. Alternatively, options can be added to the media using the Media.add_options method (with the same limitation). @param options: optional media option=value strings
def media_new(self, mrl, *options): """Create a new Media instance. If mrl contains a colon (:) preceded by more than 1 letter, it will be treated as a URL. Else, it will be considered as a local path. If you need more control, directly use media_new_location/media_new_path methods. Options can be specified as supplementary string parameters, but note that many options cannot be set at the media level, and rather at the Instance level. For instance, the marquee filter must be specified when creating the vlc.Instance or vlc.MediaPlayer. Alternatively, options can be added to the media using the Media.add_options method (with the same limitation). @param options: optional media option=value strings """ if ':' in mrl and mrl.index(':') > 1: # Assume it is a URL m = libvlc_media_new_location(self, str_to_bytes(mrl)) else: # Else it should be a local path. m = libvlc_media_new_path(self, str_to_bytes(os.path.normpath(mrl))) for o in options: libvlc_media_add_option(m, str_to_bytes(o)) m._instance = self return m
Create a new MediaList instance. @param mrls: optional list of MRL strings
def media_list_new(self, mrls=None): """Create a new MediaList instance. @param mrls: optional list of MRL strings """ l = libvlc_media_list_new(self) # We should take the lock, but since we did not leak the # reference, nobody else can access it. if mrls: for m in mrls: l.add_media(m) l._instance = self return l
Enumerate the defined audio output devices. @return: list of dicts {name:, description:, devices:}
def audio_output_enumerate_devices(self): """Enumerate the defined audio output devices. @return: list of dicts {name:, description:, devices:} """ r = [] head = libvlc_audio_output_list_get(self) if head: i = head while i: i = i.contents d = [{'id': libvlc_audio_output_device_id (self, i.name, d), 'longname': libvlc_audio_output_device_longname(self, i.name, d)} for d in range(libvlc_audio_output_device_count (self, i.name))] r.append({'name': i.name, 'description': i.description, 'devices': d}) i = i.next libvlc_audio_output_list_release(head) return r
Sets the application name. LibVLC passes this as the user agent string when a protocol requires it. @param name: human-readable application name, e.g. "FooBar player 1.2.3". @param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0". @version: LibVLC 1.1.1 or later.
def set_user_agent(self, name, http): '''Sets the application name. LibVLC passes this as the user agent string when a protocol requires it. @param name: human-readable application name, e.g. "FooBar player 1.2.3". @param http: HTTP User Agent, e.g. "FooBar/1.2.3 Python/2.6.0". @version: LibVLC 1.1.1 or later. ''' return libvlc_set_user_agent(self, str_to_bytes(name), str_to_bytes(http))
Sets some meta-information about the application. See also L{set_user_agent}(). @param id: Java-style application identifier, e.g. "com.acme.foobar". @param version: application version numbers, e.g. "1.2.3". @param icon: application icon name, e.g. "foobar". @version: LibVLC 2.1.0 or later.
def set_app_id(self, id, version, icon): '''Sets some meta-information about the application. See also L{set_user_agent}(). @param id: Java-style application identifier, e.g. "com.acme.foobar". @param version: application version numbers, e.g. "1.2.3". @param icon: application icon name, e.g. "foobar". @version: LibVLC 2.1.0 or later. ''' return libvlc_set_app_id(self, str_to_bytes(id), str_to_bytes(version), str_to_bytes(icon))
Create a media with custom callbacks to read the data from. @param open_cb: callback to open the custom bitstream input media. @param read_cb: callback to read data (must not be NULL). @param seek_cb: callback to seek, or NULL if seeking is not supported. @param close_cb: callback to close the media, or NULL if unnecessary. @param opaque: data pointer for the open callback. @return: the newly created media or NULL on error @note If open_cb is NULL, the opaque pointer will be passed to read_cb, seek_cb and close_cb, and the stream size will be treated as unknown. @note The callbacks may be called asynchronously (from another thread). A single stream instance need not be reentrant. However the open_cb needs to be reentrant if the media is used by multiple player instances. @warning The callbacks may be used until all or any player instances that were supplied the media item are stopped. See L{media_release}. @version: LibVLC 3.0.0 and later.
def media_new_callbacks(self, open_cb, read_cb, seek_cb, close_cb, opaque): '''Create a media with custom callbacks to read the data from. @param open_cb: callback to open the custom bitstream input media. @param read_cb: callback to read data (must not be NULL). @param seek_cb: callback to seek, or NULL if seeking is not supported. @param close_cb: callback to close the media, or NULL if unnecessary. @param opaque: data pointer for the open callback. @return: the newly created media or NULL on error @note If open_cb is NULL, the opaque pointer will be passed to read_cb, seek_cb and close_cb, and the stream size will be treated as unknown. @note The callbacks may be called asynchronously (from another thread). A single stream instance need not be reentrant. However the open_cb needs to be reentrant if the media is used by multiple player instances. @warning The callbacks may be used until all or any player instances that were supplied the media item are stopped. See L{media_release}. @version: LibVLC 3.0.0 and later. ''' return libvlc_media_new_callbacks(self, open_cb, read_cb, seek_cb, close_cb, opaque)
Add a broadcast, with one input. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error.
def vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): '''Add a broadcast, with one input. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_broadcast(self, str_to_bytes(psz_name), str_to_bytes(psz_input), str_to_bytes(psz_output), i_options, ppsz_options, b_enabled, b_loop)
Add a vod, with one input. @param psz_name: the name of the new vod media. @param psz_input: the input MRL. @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new vod. @param psz_mux: the muxer of the vod media. @return: 0 on success, -1 on error.
def vlm_add_vod(self, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux): '''Add a vod, with one input. @param psz_name: the name of the new vod media. @param psz_input: the input MRL. @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new vod. @param psz_mux: the muxer of the vod media. @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_vod(self, str_to_bytes(psz_name), str_to_bytes(psz_input), i_options, ppsz_options, b_enabled, str_to_bytes(psz_mux))
Set the output for a media. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error.
def vlm_set_output(self, psz_name, psz_output): '''Set the output for a media. @param psz_name: the media to work on. @param psz_output: the output MRL (the parameter to the "sout" variable). @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_output(self, str_to_bytes(psz_name), str_to_bytes(psz_output))
Set a media's input MRL. This will delete all existing inputs and add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error.
def vlm_set_input(self, psz_name, psz_input): '''Set a media's input MRL. This will delete all existing inputs and add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_input(self, str_to_bytes(psz_name), str_to_bytes(psz_input))
Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error.
def vlm_add_input(self, psz_name, psz_input): '''Add a media's input MRL. This will add the specified one. @param psz_name: the media to work on. @param psz_input: the input MRL. @return: 0 on success, -1 on error. ''' return libvlc_vlm_add_input(self, str_to_bytes(psz_name), str_to_bytes(psz_input))
Set a media's vod muxer. @param psz_name: the media to work on. @param psz_mux: the new muxer. @return: 0 on success, -1 on error.
def vlm_set_mux(self, psz_name, psz_mux): '''Set a media's vod muxer. @param psz_name: the media to work on. @param psz_mux: the new muxer. @return: 0 on success, -1 on error. ''' return libvlc_vlm_set_mux(self, str_to_bytes(psz_name), str_to_bytes(psz_mux))
Edit the parameters of a media. This will delete all existing inputs and add the specified one. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error.
def vlm_change_media(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop): '''Edit the parameters of a media. This will delete all existing inputs and add the specified one. @param psz_name: the name of the new broadcast. @param psz_input: the input MRL. @param psz_output: the output MRL (the parameter to the "sout" variable). @param i_options: number of additional options. @param ppsz_options: additional options. @param b_enabled: boolean for enabling the new broadcast. @param b_loop: Should this broadcast be played in loop ? @return: 0 on success, -1 on error. ''' return libvlc_vlm_change_media(self, str_to_bytes(psz_name), str_to_bytes(psz_input), str_to_bytes(psz_output), i_options, ppsz_options, b_enabled, b_loop)
Get media descriptor's elementary streams description Note, you need to call L{parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. The result must be freed with L{tracks_release}. @version: LibVLC 2.1.0 and later.
def tracks_get(self): """Get media descriptor's elementary streams description Note, you need to call L{parse}() or play the media at least once before calling this function. Not doing this will result in an empty array. The result must be freed with L{tracks_release}. @version: LibVLC 2.1.0 and later. """ mediaTrack_pp = ctypes.POINTER(MediaTrack)() n = libvlc_media_tracks_get(self, byref(mediaTrack_pp)) info = cast(ctypes.mediaTrack_pp, ctypes.POINTER(ctypes.POINTER(MediaTrack) * n)) return info
Add media instance to media list. The L{lock} should be held upon entering this function. @param mrl: a media instance or a MRL. @return: 0 on success, -1 if the media list is read-only.
def add_media(self, mrl): """Add media instance to media list. The L{lock} should be held upon entering this function. @param mrl: a media instance or a MRL. @return: 0 on success, -1 if the media list is read-only. """ if isinstance(mrl, basestring): mrl = (self.get_instance() or get_default_instance()).media_new(mrl) return libvlc_media_list_add_media(self, mrl)
Set the MRL to play. Warning: most audio and video options, such as text renderer, have no effects on an individual media. These options must be set at the vlc.Instance or vlc.MediaPlayer instanciation. @param mrl: The MRL @param options: optional media option=value strings @return: the Media object
def set_mrl(self, mrl, *options): """Set the MRL to play. Warning: most audio and video options, such as text renderer, have no effects on an individual media. These options must be set at the vlc.Instance or vlc.MediaPlayer instanciation. @param mrl: The MRL @param options: optional media option=value strings @return: the Media object """ m = self.get_instance().media_new(mrl, *options) self.set_media(m) return m
Get the video size in pixels as 2-tuple (width, height). @param num: video number (default 0).
def video_get_size(self, num=0): """Get the video size in pixels as 2-tuple (width, height). @param num: video number (default 0). """ r = libvlc_video_get_size(self, num) if isinstance(r, tuple) and len(r) == 2: return r else: raise VLCException('invalid video number (%s)' % (num,))
Set a Win32/Win64 API window handle (HWND). Specify where the media player should render its video output. If LibVLC was built without Win32/Win64 API output support, then this has no effects. @param drawable: windows handle of the drawable.
def set_hwnd(self, drawable): """Set a Win32/Win64 API window handle (HWND). Specify where the media player should render its video output. If LibVLC was built without Win32/Win64 API output support, then this has no effects. @param drawable: windows handle of the drawable. """ if not isinstance(drawable, ctypes.c_void_p): drawable = ctypes.c_void_p(int(drawable)) libvlc_media_player_set_hwnd(self, drawable)
Get the mouse pointer coordinates over a video as 2-tuple (x, y). Coordinates are expressed in terms of the decoded video resolution, B{not} in terms of pixels on the screen/viewport. To get the latter, you must query your windowing system directly. Either coordinate may be negative or larger than the corresponding size of the video, if the cursor is outside the rendering area. @warning: The coordinates may be out-of-date if the pointer is not located on the video rendering area. LibVLC does not track the mouse pointer if the latter is outside the video widget. @note: LibVLC does not support multiple mouse pointers (but does support multiple input devices sharing the same pointer). @param num: video number (default 0).
def video_get_cursor(self, num=0): """Get the mouse pointer coordinates over a video as 2-tuple (x, y). Coordinates are expressed in terms of the decoded video resolution, B{not} in terms of pixels on the screen/viewport. To get the latter, you must query your windowing system directly. Either coordinate may be negative or larger than the corresponding size of the video, if the cursor is outside the rendering area. @warning: The coordinates may be out-of-date if the pointer is not located on the video rendering area. LibVLC does not track the mouse pointer if the latter is outside the video widget. @note: LibVLC does not support multiple mouse pointers (but does support multiple input devices sharing the same pointer). @param num: video number (default 0). """ r = libvlc_video_get_cursor(self, num) if isinstance(r, tuple) and len(r) == 2: return r raise VLCException('invalid video number (%s)' % (num,))
Set callbacks and private data to render decoded video to a custom area in memory. Use L{video_set_format}() or L{video_set_format_callbacks}() to configure the decoded format. @param lock: callback to lock video memory (must not be NULL). @param unlock: callback to unlock video memory (or NULL if not needed). @param display: callback to display video (or NULL if not needed). @param opaque: private pointer for the three callbacks (as first parameter). @version: LibVLC 1.1.1 or later.
def video_set_callbacks(self, lock, unlock, display, opaque): '''Set callbacks and private data to render decoded video to a custom area in memory. Use L{video_set_format}() or L{video_set_format_callbacks}() to configure the decoded format. @param lock: callback to lock video memory (must not be NULL). @param unlock: callback to unlock video memory (or NULL if not needed). @param display: callback to display video (or NULL if not needed). @param opaque: private pointer for the three callbacks (as first parameter). @version: LibVLC 1.1.1 or later. ''' return libvlc_video_set_callbacks(self, lock, unlock, display, opaque)
Set decoded video chroma and dimensions. This only works in combination with L{video_set_callbacks}(), and is mutually exclusive with L{video_set_format_callbacks}(). @param chroma: a four-characters string identifying the chroma (e.g. "RV32" or "YUYV"). @param width: pixel width. @param height: pixel height. @param pitch: line pitch (in bytes). @version: LibVLC 1.1.1 or later. @bug: All pixel planes are expected to have the same pitch. To use the YCbCr color space with chrominance subsampling, consider using L{video_set_format_callbacks}() instead.
def video_set_format(self, chroma, width, height, pitch): '''Set decoded video chroma and dimensions. This only works in combination with L{video_set_callbacks}(), and is mutually exclusive with L{video_set_format_callbacks}(). @param chroma: a four-characters string identifying the chroma (e.g. "RV32" or "YUYV"). @param width: pixel width. @param height: pixel height. @param pitch: line pitch (in bytes). @version: LibVLC 1.1.1 or later. @bug: All pixel planes are expected to have the same pitch. To use the YCbCr color space with chrominance subsampling, consider using L{video_set_format_callbacks}() instead. ''' return libvlc_video_set_format(self, str_to_bytes(chroma), width, height, pitch)
Set callbacks and private data for decoded audio. Use L{audio_set_format}() or L{audio_set_format_callbacks}() to configure the decoded audio format. @param play: callback to play audio samples (must not be NULL). @param pause: callback to pause playback (or NULL to ignore). @param resume: callback to resume playback (or NULL to ignore). @param flush: callback to flush audio buffers (or NULL to ignore). @param drain: callback to drain audio buffers (or NULL to ignore). @param opaque: private pointer for the audio callbacks (as first parameter). @version: LibVLC 2.0.0 or later.
def audio_set_callbacks(self, play, pause, resume, flush, drain, opaque): '''Set callbacks and private data for decoded audio. Use L{audio_set_format}() or L{audio_set_format_callbacks}() to configure the decoded audio format. @param play: callback to play audio samples (must not be NULL). @param pause: callback to pause playback (or NULL to ignore). @param resume: callback to resume playback (or NULL to ignore). @param flush: callback to flush audio buffers (or NULL to ignore). @param drain: callback to drain audio buffers (or NULL to ignore). @param opaque: private pointer for the audio callbacks (as first parameter). @version: LibVLC 2.0.0 or later. ''' return libvlc_audio_set_callbacks(self, play, pause, resume, flush, drain, opaque)
Set decoded audio format. This only works in combination with L{audio_set_callbacks}(), and is mutually exclusive with L{audio_set_format_callbacks}(). @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param rate: sample rate (expressed in Hz). @param channels: channels count. @version: LibVLC 2.0.0 or later.
def audio_set_format(self, format, rate, channels): '''Set decoded audio format. This only works in combination with L{audio_set_callbacks}(), and is mutually exclusive with L{audio_set_format_callbacks}(). @param format: a four-characters string identifying the sample format (e.g. "S16N" or "FL32"). @param rate: sample rate (expressed in Hz). @param channels: channels count. @version: LibVLC 2.0.0 or later. ''' return libvlc_audio_set_format(self, str_to_bytes(format), rate, channels)
Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param num: number of video output (typically 0 for the first/only one). @param psz_filepath: the path where to save the screenshot to. @param i_width: the snapshot's width. @param i_height: the snapshot's height. @return: 0 on success, -1 if the video was not found.
def video_take_snapshot(self, num, psz_filepath, i_width, i_height): '''Take a snapshot of the current video window. If i_width AND i_height is 0, original size is used. If i_width XOR i_height is 0, original aspect-ratio is preserved. @param num: number of video output (typically 0 for the first/only one). @param psz_filepath: the path where to save the screenshot to. @param i_width: the snapshot's width. @param i_height: the snapshot's height. @return: 0 on success, -1 if the video was not found. ''' return libvlc_video_take_snapshot(self, num, str_to_bytes(psz_filepath), i_width, i_height)
Configures an explicit audio output device. If the module paramater is NULL, audio output will be moved to the device specified by the device identifier string immediately. This is the recommended usage. A list of adequate potential device strings can be obtained with L{audio_output_device_enum}(). However passing NULL is supported in LibVLC version 2.2.0 and later only; in earlier versions, this function would have no effects when the module parameter was NULL. If the module parameter is not NULL, the device parameter of the corresponding audio output, if it exists, will be set to the specified string. Note that some audio output modules do not have such a parameter (notably MMDevice and PulseAudio). A list of adequate potential device strings can be obtained with L{audio_output_device_list_get}(). @note: This function does not select the specified audio output plugin. L{audio_output_set}() is used for that purpose. @warning: The syntax for the device parameter depends on the audio output. Some audio output modules require further parameters (e.g. a channels map in the case of ALSA). @param module: If NULL, current audio output module. if non-NULL, name of audio output module. @param device_id: device identifier string. @return: Nothing. Errors are ignored (this is a design bug).
def audio_output_device_set(self, module, device_id): '''Configures an explicit audio output device. If the module paramater is NULL, audio output will be moved to the device specified by the device identifier string immediately. This is the recommended usage. A list of adequate potential device strings can be obtained with L{audio_output_device_enum}(). However passing NULL is supported in LibVLC version 2.2.0 and later only; in earlier versions, this function would have no effects when the module parameter was NULL. If the module parameter is not NULL, the device parameter of the corresponding audio output, if it exists, will be set to the specified string. Note that some audio output modules do not have such a parameter (notably MMDevice and PulseAudio). A list of adequate potential device strings can be obtained with L{audio_output_device_list_get}(). @note: This function does not select the specified audio output plugin. L{audio_output_set}() is used for that purpose. @warning: The syntax for the device parameter depends on the audio output. Some audio output modules require further parameters (e.g. a channels map in the case of ALSA). @param module: If NULL, current audio output module. if non-NULL, name of audio output module. @param device_id: device identifier string. @return: Nothing. Errors are ignored (this is a design bug). ''' return libvlc_audio_output_device_set(self, str_to_bytes(module), str_to_bytes(device_id))
Do or redo the action
def do(self): 'Do or redo the action' self._runner = self._generator(*self.args, **self.kwargs) rets = next(self._runner) if isinstance(rets, tuple): self._text = rets[0] return rets[1:] elif rets is None: self._text = '' return None else: self._text = rets return None
Decorator which creates a new undoable action type. This decorator should be used on a generator of the following format:: @undoable def operation(*args): do_operation_code yield 'descriptive text' undo_operator_code
def undoable(generator): ''' Decorator which creates a new undoable action type. This decorator should be used on a generator of the following format:: @undoable def operation(*args): do_operation_code yield 'descriptive text' undo_operator_code ''' def inner(*args, **kwargs): action = _Action(generator, args, kwargs) ret = action.do() stack().append(action) if isinstance(ret, tuple): if len(ret) == 1: return ret[0] elif len(ret) == 0: return None return ret return inner
Redo the last undone action. This is only possible if no other actions have occurred since the last undo call.
def redo(self): ''' Redo the last undone action. This is only possible if no other actions have occurred since the last undo call. ''' if self.canredo(): undoable = self._redos.pop() with self._pausereceiver(): try: undoable.do() except: self.clear() raise else: self._undos.append(undoable) self.docallback()
Undo the last action.
def undo(self): ''' Undo the last action. ''' if self.canundo(): undoable = self._undos.pop() with self._pausereceiver(): try: undoable.undo() except: self.clear() raise else: self._redos.append(undoable) self.undocallback()
Clear the undo list.
def clear(self): ''' Clear the undo list. ''' self._undos.clear() self._redos.clear() self._savepoint = None self._receiver = self._undos
Add a undoable to the stack, using ``receiver.append()``.
def append(self, action): ''' Add a undoable to the stack, using ``receiver.append()``. ''' if self._receiver is not None: self._receiver.append(action) if self._receiver is self._undos: self._redos.clear() self.docallback()
Returns bounding box (xmin, xmax, ymin, ymax)
def get_bbox(self): """Returns bounding box (xmin, xmax, ymin, ymax)""" x_min = self.x x_max = x_min + self.width y_min = self.y y_max = self.y + self.height return x_min, x_max, y_min, y_max
Returns False iif bounding boxed of self and other intersect
def is_bbox_not_intersecting(self, other): """Returns False iif bounding boxed of self and other intersect""" self_x_min, self_x_max, self_y_min, self_y_max = self.get_bbox() other_x_min, other_x_max, other_y_min, other_y_max = other.get_bbox() return \ self_x_min > other_x_max or \ other_x_min > self_x_max or \ self_y_min > other_y_max or \ other_y_min > self_y_max
Returns True iif point is inside the rectangle (border included) Parameters ---------- * pt_x: Number \tx-value of point * pt_y: Number \ty-value of point
def is_point_in_rect(self, pt_x, pt_y): """Returns True iif point is inside the rectangle (border included) Parameters ---------- * pt_x: Number \tx-value of point * pt_y: Number \ty-value of point """ x_min, x_max, y_min, y_max = self.get_bbox() return x_min <= pt_x <= x_max and y_min <= pt_y <= y_max
Returns bounding box (xmin, xmax, ymin, ymax)
def get_bbox(self): """Returns bounding box (xmin, xmax, ymin, ymax)""" width = self.width height = self.height cos_angle = cos(self.angle) sin_angle = sin(self.angle) x_diff = 0.5 * width y_diff = 0.5 * height # self rotates around (0, 0). c_x_diff = cos_angle * x_diff s_x_diff = sin_angle * x_diff c_y_diff = cos_angle * y_diff s_y_diff = sin_angle * y_diff if cos_angle > 0: if sin_angle > 0: x_max = c_x_diff + s_y_diff x_min = -x_max y_max = c_y_diff + s_x_diff y_min = -y_max else: # sin_angle <= 0.0 x_max = c_x_diff - s_y_diff x_min = -x_max y_max = c_y_diff - s_x_diff y_min = -y_max else: # cos(angle) <= 0.0 if sin_angle > 0: x_min = c_x_diff - s_y_diff x_max = -x_min y_min = c_y_diff - s_x_diff y_max = -y_min else: # sin_angle <= 0.0 x_min = c_x_diff + s_y_diff x_max = -x_min y_min = c_y_diff + s_x_diff y_max = -y_min return x_min, x_max, y_min, y_max
Returns False iif any edge excludes all vertices of other.
def is_edge_not_excluding_vertices(self, other): """Returns False iif any edge excludes all vertices of other.""" c_a = cos(self.angle) s_a = sin(self.angle) # Get min and max of other. other_x_min, other_x_max, other_y_min, other_y_max = other.get_bbox() self_x_diff = 0.5 * self.width self_y_diff = 0.5 * self.height if c_a > 0: if s_a > 0: return \ c_a * other_x_max + s_a * other_y_max < -self_x_diff or \ c_a * other_x_min + s_a * other_y_min > self_x_diff or \ c_a * other_y_max - s_a * other_x_min < -self_y_diff or \ c_a * other_y_min - s_a * other_x_max > self_y_diff else: # s_a <= 0.0 return \ c_a * other_x_max + s_a * other_y_min < -self_x_diff or \ c_a * other_x_min + s_a * other_y_max > self_x_diff or \ c_a * other_y_max - s_a * other_x_max < -self_y_diff or \ c_a * other_y_min - s_a * other_x_min > self_y_diff else: # c_a <= 0.0 if s_a > 0: return \ c_a * other_x_min + s_a * other_y_max < -self_x_diff or \ c_a * other_x_max + s_a * other_y_min > self_x_diff or \ c_a * other_y_min - s_a * other_x_min < -self_y_diff or \ c_a * other_y_max - s_a * other_x_max > self_y_diff else: # s_a <= 0.0 return \ c_a * other_x_min + s_a * other_y_min < -self_x_diff or \ c_a * other_x_max + s_a * other_y_max > self_x_diff or \ c_a * other_y_min - s_a * other_x_max < -self_y_diff or \ c_a * other_y_max - s_a * other_x_min > self_y_diff
Returns collision with axis aligned rect
def collides(self, other): """Returns collision with axis aligned rect""" angle = self.angle width = self.width height = self.height if angle == 0: return other.collides(Rect(-0.5 * width, -0.5 * height, width, height)) # Phase 1 # # * Form bounding box on tilted rectangle P. # * Check whether bounding box and other intersect. # * If not, then self and other do not intersect. # * Otherwise proceed to Phase 2. # Now perform the standard rectangle intersection test. if self.is_bbox_not_intersecting(other): return False # Phase 2 # # If we get here, check the edges of self to see # * if one of them excludes all vertices of other. # * If so, then self and other do not intersect. # * (If not, then self and other do intersect.) return not self.is_edge_not_excluding_vertices(other)
Returns vector from left to right
def get_vec_lr(self): """Returns vector from left to right""" return self.width * self.cos_a(), -self.width * self.sin_a()
Returns vector from top to bottom
def get_vec_tb(self): """Returns vector from top to bottom""" return self.height * self.sin_a(), self.height * self.cos_a()
Returns rectangle center
def get_center(self): """Returns rectangle center""" lr_x, lr_y = self.get_vec_lr() tb_x, tb_y = self.get_vec_tb() center_x = self.x + (lr_x + tb_x) / 2.0 center_y = self.y + (lr_y + tb_y) / 2.0 return center_x, center_y
Returns 2-tuples for each edge top_left top_right bottom_left bottom_right
def get_edges(self): """Returns 2-tuples for each edge top_left top_right bottom_left bottom_right """ lr_x, lr_y = self.get_vec_lr() tb_x, tb_y = self.get_vec_tb() top_left = self.x, self.y top_right = self.x + lr_x, self.y + lr_y bottom_left = self.x + tb_x, self.y + tb_y bottom_right = self.x + lr_x + tb_x, self.y + lr_y + tb_y return top_left, top_right, bottom_left, bottom_right
Returns collision with axis aligned other rect
def collides_axisaligned_rect(self, other): """Returns collision with axis aligned other rect""" # Shift both rects so that self is centered at origin self_shifted = RotoOriginRect(self.width, self.height, -self.angle) s_a = self.sin_a() c_a = self.cos_a() center_x = self.x + self.width / 2.0 * c_a - self.height / 2.0 * s_a center_y = self.y - self.height / 2.0 * c_a - self.width / 2.0 * s_a other_shifted = Rect(other.x - center_x, other.y - center_y, other.width, other.height) # Calculate collision return self_shifted.collides(other_shifted)
Returns tuple of theme, icon, action and toggle paths
def get_paths(self, theme, icon_size): """Returns tuple of theme, icon, action and toggle paths""" _size_str = "x".join(map(str, icon_size)) theme_path = get_program_path() + "share" + os.sep + "icons" + os.sep icon_path = theme_path + theme + os.sep + _size_str + os.sep action_path = icon_path + "actions" + os.sep toggle_path = icon_path + "toggles" + os.sep return theme_path, icon_path, action_path, toggle_path
Adds custom images to Artprovider
def CreateBitmap(self, artid, client, size): """Adds custom images to Artprovider""" if artid in self.extra_icons: return wx.Bitmap(self.extra_icons[artid], wx.BITMAP_TYPE_ANY) else: return wx.ArtProvider.GetBitmap(artid, client, size)
Sets class state from kwargs attributes, pops extra kwargs
def set_initial_state(self, kwargs): """Sets class state from kwargs attributes, pops extra kwargs""" self.main_window = kwargs.pop("main_window") try: statustext = kwargs.pop("statustext") except KeyError: statustext = "" try: self.total_lines = kwargs.pop("total_lines") self.statustext = statustext + \ _("{nele} of {totalele} elements processed.") except KeyError: self.total_lines = None self.statustext = statustext + _("{nele} elements processed.") try: self.freq = kwargs.pop("freq") except KeyError: self.freq = 1000 # The aborted attribute makes next() to raise StopIteration self.aborted = False # Line counter self.line = 0 # Bindings self.main_window.Bind(wx.EVT_KEY_DOWN, self.on_key)
Next that shows progress in statusbar for each <freq> cells
def next(self): """Next that shows progress in statusbar for each <freq> cells""" self.progress_status() # Check abortes state and raise StopIteration if aborted if self.aborted: statustext = _("File loading aborted.") post_command_event(self.main_window, self.main_window.StatusBarMsg, text=statustext) raise StopIteration return self.parent_cls.next(self)
Write that shows progress in statusbar for each <freq> cells
def write(self, *args, **kwargs): """Write that shows progress in statusbar for each <freq> cells""" self.progress_status() # Check abortes state and raise StopIteration if aborted if self.aborted: statustext = _("File saving aborted.") post_command_event(self.main_window, self.main_window.StatusBarMsg, text=statustext) return False return self.parent_cls.write(self, *args, **kwargs)
Displays progress in statusbar
def progress_status(self): """Displays progress in statusbar""" if self.line % self.freq == 0: text = self.statustext.format(nele=self.line, totalele=self.total_lines) if self.main_window.grid.actions.pasting: try: post_command_event(self.main_window, self.main_window.StatusBarMsg, text=text) except TypeError: # The main window does not exist any more pass else: # Write directly to the status bar because the event queue # is not emptied during file access self.main_window.GetStatusBar().SetStatusText(text) # Now wait for the statusbar update to be written on screen if is_gtk(): try: wx.Yield() except: pass self.line += 1
Sets aborted state if escape is pressed
def on_key(self, event): """Sets aborted state if escape is pressed""" if self.main_window.grid.actions.pasting and \ event.GetKeyCode() == wx.WXK_ESCAPE: self.aborted = True event.Skip()
Plots histogram
def hist(data): """Plots histogram""" win = CurveDialog(edit=False, toolbar=True, wintitle="Histogram test") plot = win.get_plot() plot.add_item(make.histogram(data)) win.show() win.exec_()
Returns list of table nodes from ods object
def _get_tables(self, ods): """Returns list of table nodes from ods object""" childnodes = ods.spreadsheet.childNodes qname_childnodes = [(s.qname[1], s) for s in childnodes] return [node for name, node in qname_childnodes if name == u"table"]
Returns rows from table
def _get_rows(self, table): """Returns rows from table""" childnodes = table.childNodes qname_childnodes = [(s.qname[1], s) for s in childnodes] return [node for name, node in qname_childnodes if name == u'table-row']
Returns rows from row
def _get_cells(self, row): """Returns rows from row""" childnodes = row.childNodes qname_childnodes = [(s.qname[1], s) for s in childnodes] return [node for name, node in qname_childnodes if name == u'table-cell']
Updates code in code_array
def _ods2code(self): """Updates code in code_array""" ods = ODSReader(self.ods_file, clonespannedcolumns=True) tables = ods.sheets for tab_id, table in enumerate(tables): for row_id in xrange(len(table)): for col_id in xrange(len(table[row_id])): key = row_id, col_id, tab_id text = unicode(table[row_id][col_id]) self.code_array[key] = text
Holds application main loop
def pyspread(S=None): """Holds application main loop""" # Initialize main application app = MainApplication(S=S, redirect=False) app.MainLoop()
Returns a a tuple (options, filename) options: The command line options filename: String (defaults to None) \tThe name of the file that is loaded on start-up
def parse(self): """ Returns a a tuple (options, filename) options: The command line options filename: String (defaults to None) \tThe name of the file that is loaded on start-up """ options, args = self.parser.parse_args() # If one dimension is 0 then the grid has no cells if min(options.dimensions) < 1: print(_("Cell dimension must be > 0.")) sys.exit() # No MDI yet, pyspread can be started several times though if len(args) > 1: print(_("Only one file may be opened at a time.")) sys.exit() filename = None if len(args) == 1: # A filename is provided and hence opened filename = args[0] else: filename = None return options, filename
Init class that is automatically run on __init__
def OnInit(self): """Init class that is automatically run on __init__""" # Get command line options and arguments cmdp = Commandlineparser() options, filename = cmdp.parse() kwargs = { "title": "pyspread", "S": self.S } # Store command line input in config if no file is provided if filename is None: kwargs["dimensions"] = options.dimensions # Main window creation from src.gui._main_window import MainWindow self.main_window = MainWindow(None, **kwargs) # Initialize file loading via event if gnupg is not None and options.new_gpgkey: # Create GPG key if not present try: from src.lib.gpg import genkey self.config["gpg_key_fingerprint"] = repr("") genkey() except ImportError: pass except ValueError: # python-gnupg is installed but gnupg is not installed pass # Show application window self.SetTopWindow(self.main_window) self.main_window.Show() # Load filename if provided if filename is not None: post_command_event(self.main_window, self.GridActionOpenMsg, attr={"filepath": filename}) self.main_window.filepath = filename return True
Reads a sheet in the sheet dictionary Stores each sheet as an array (rows) of arrays (columns)
def readSheet(self, sheet): """Reads a sheet in the sheet dictionary Stores each sheet as an array (rows) of arrays (columns) """ name = sheet.getAttribute("name") rows = sheet.getElementsByType(TableRow) arrRows = [] # for each row for row in rows: row_comment = "" arrCells = GrowingList() cells = row.getElementsByType(TableCell) # for each cell count = 0 for cell in cells: # repeated value? repeat = cell.getAttribute("numbercolumnsrepeated") if(not repeat): repeat = 1 spanned = \ int(cell.getAttribute('numbercolumnsspanned') or 0) # clone spanned cells if self.clonespannedcolumns is not None and spanned > 1: repeat = spanned ps = cell.getElementsByType(P) textContent = "" # for each text/text:span node for p in ps: for n in p.childNodes: if (n.nodeType == 1 and n.tagName == "text:span"): for c in n.childNodes: if (c.nodeType == 3): textContent = u'{}{}'.format(textContent, n.data) if (n.nodeType == 3): textContent = u'{}{}'.format(textContent, n.data) if(textContent): if(textContent[0] != "#"): # ignore comments cells for rr in xrange(int(repeat)): # repeated? arrCells[count]=textContent count+=1 else: row_comment = row_comment + textContent + " " else: for rr in xrange(int(repeat)): count+=1 # if row contained something if(len(arrCells)): arrRows.append(arrCells) #else: # print ("Empty or commented row (", row_comment, ")") self.sheets.append(arrRows) self.sheet_names.append(name)
Sniffs CSV dialect and header info from csvfilepath Returns a tuple of dialect and has_header
def sniff(filepath): """ Sniffs CSV dialect and header info from csvfilepath Returns a tuple of dialect and has_header """ with open(filepath, "rb") as csvfile: sample = csvfile.read(config["sniff_size"]) sniffer = csv.Sniffer() dialect = sniffer.sniff(sample)() has_header = sniffer.has_header(sample) return dialect, has_header
Returns List of first line items of file filepath
def get_first_line(filepath, dialect): """Returns List of first line items of file filepath""" with open(filepath, "rb") as csvfile: csvreader = csv.reader(csvfile, dialect=dialect) for first_line in csvreader: break return first_line
Returns list of digested values in line
def digested_line(line, digest_types): """Returns list of digested values in line""" digested_line = [] for i, ele in enumerate(line): try: digest_key = digest_types[i] except IndexError: digest_key = digest_types[0] digest = Digest(acceptable_types=[digest_key]) try: digested_line.append(repr(digest(ele))) except Exception: digested_line.append("") return digested_line
Generator of digested values from csv file in filepath Parameters ---------- filepath:String \tFile path of csv file to read dialect: Object \tCsv dialect digest_types: tuple of types \tTypes of data for each col
def csv_digest_gen(filepath, dialect, has_header, digest_types): """Generator of digested values from csv file in filepath Parameters ---------- filepath:String \tFile path of csv file to read dialect: Object \tCsv dialect digest_types: tuple of types \tTypes of data for each col """ with open(filepath, "rb") as csvfile: csvreader = csv.reader(csvfile, dialect=dialect) if has_header: # Ignore first line for line in csvreader: break for line in csvreader: yield digested_line(line, digest_types)
Generator of row, col, value tuple from iterable of iterables it: Iterable of iterables \tMatrix that shall be mapped on target grid shape: Tuple of Integer \tShape of target grid topleft: 2-tuple of Integer \tTop left cell for insertion of it
def cell_key_val_gen(iterable, shape, topleft=(0, 0)): """Generator of row, col, value tuple from iterable of iterables it: Iterable of iterables \tMatrix that shall be mapped on target grid shape: Tuple of Integer \tShape of target grid topleft: 2-tuple of Integer \tTop left cell for insertion of it """ top, left = topleft for __row, line in enumerate(iterable): row = top + __row if row >= shape[0]: break for __col, value in enumerate(line): col = left + __col if col >= shape[1]: break yield row, col, value
Encodes all Unicode strings in line to encoding Parameters ---------- line: Iterable of Unicode strings \tDate to be encoded encoding: String, defaults to "utf-8" \tTarget encoding
def encode_gen(line, encoding="utf-8"): """Encodes all Unicode strings in line to encoding Parameters ---------- line: Iterable of Unicode strings \tDate to be encoded encoding: String, defaults to "utf-8" \tTarget encoding """ for ele in line: if isinstance(ele, types.UnicodeType): yield ele.encode(encoding) else: yield ele
Generator of values in a csv line
def _get_csv_cells_gen(self, line): """Generator of values in a csv line""" digest_types = self.digest_types for j, value in enumerate(line): if self.first_line: digest_key = None digest = lambda x: x.decode(self.encoding) else: try: digest_key = digest_types[j] except IndexError: digest_key = digest_types[0] digest = Digest(acceptable_types=[digest_key], encoding=self.encoding) try: digest_res = digest(value) if digest_res == "\b": digest_res = None elif digest_key is not types.CodeType: digest_res = repr(digest_res) except Exception: digest_res = "" yield digest_res
Writes values from iterable into CSV file
def write(self, iterable): """Writes values from iterable into CSV file""" io_error_text = _("Error writing to file {filepath}.") io_error_text = io_error_text.format(filepath=self.path) try: with open(self.path, "wb") as csvfile: csv_writer = csv.writer(csvfile, self.dialect) for line in iterable: csv_writer.writerow( list(encode_gen(line, encoding=self.encoding))) except IOError: txt = \ _("Error opening file {filepath}.").format(filepath=self.path) try: post_command_event(self.main_window, self.StatusBarMsg, text=txt) except TypeError: # The main window does not exist any more pass return False
Get an Excel index from
def color2idx(self, red, green, blue): """Get an Excel index from""" xlwt_colors = [ (0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (0, 0, 0), (255, 255, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (128, 0, 0), (0, 128, 0), (0, 0, 128), (128, 128, 0), (128, 0, 128), (0, 128, 128), (192, 192, 192), (128, 128, 128), (153, 153, 255), (153, 51, 102), (255, 255, 204), (204, 255, 255), (102, 0, 102), (255, 128, 128), (0, 102, 204), (204, 204, 255), (0, 0, 128), (255, 0, 255), (255, 255, 0), (0, 255, 255), (128, 0, 128), (128, 0, 0), (0, 128, 128), (0, 0, 255), (0, 204, 255), (204, 255, 255), (204, 255, 204), (255, 255, 153), (153, 204, 255), (255, 153, 204), (204, 153, 255), (255, 204, 153), (51, 102, 255), (51, 204, 204), (153, 204, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0), (102, 102, 153), (150, 150, 150), (0, 51, 102), (51, 153, 102), (0, 51, 0), (51, 51, 0), (153, 51, 0), (153, 51, 102), (51, 51, 153), (51, 51, 51) ] distances = [abs(red - r) + abs(green - g) + abs(blue - b) for r, g, b in xlwt_colors] min_dist_idx = distances.index(min(distances)) return min_dist_idx
Writes shape to xls file Format: <rows>\t<cols>\t<tabs>\n
def _shape2xls(self, worksheets): """Writes shape to xls file Format: <rows>\t<cols>\t<tabs>\n """ __, __, tabs = self.code_array.shape if tabs > self.xls_max_tabs: tabs = self.xls_max_tabs for tab in xrange(tabs): worksheet = self.workbook.add_sheet(str(tab)) worksheets.append(worksheet)
Updates shape in code_array
def _xls2shape(self): """Updates shape in code_array""" sheets = self.workbook.sheets() nrows = 1 ncols = 1 for sheet in sheets: nrows = max(nrows, sheet.nrows) ncols = max(ncols, sheet.ncols) ntabs = len(sheets) self.code_array.shape = nrows, ncols, ntabs
Writes code to xls file Format: <row>\t<col>\t<tab>\t<code>\n
def _code2xls(self, worksheets): """Writes code to xls file Format: <row>\t<col>\t<tab>\t<code>\n """ code_array = self.code_array xls_max_shape = self.xls_max_rows, self.xls_max_cols, self.xls_max_tabs for key in code_array: if all(kele < mele for kele, mele in zip(key, xls_max_shape)): # Cell lies within Excel boundaries row, col, tab = key code_str = code_array(key) if code_str is not None: style = self._get_xfstyle(worksheets, key) worksheets[tab].write(row, col, label=code_str, style=style) # Handle cell formatting in cells without code # Get bboxes for all cell_attributes max_shape = [min(xls_max_shape[0], code_array.shape[0]), min(xls_max_shape[1], code_array.shape[1])] # Prevent systems from blocking if max_shape[0] * max_shape[1] > 1024000: # Ignore all cell attributes below row 3999 max_shape[0] = 4000 cell_attributes = code_array.dict_grid.cell_attributes bboxes = [] for s, __tab, __ in cell_attributes: if s: bboxes.append((s.get_grid_bbox(code_array.shape), __tab)) # Get bbox_cell_set from bboxes cells = [] for ((bb_top, bb_left), (bb_bottom, bb_right)), __tab in bboxes: __bb_bottom = min(bb_bottom, max_shape[0]) __bb_right = min(bb_right, max_shape[1]) for __row, __col in product(xrange(bb_top, __bb_bottom + 1), xrange(bb_left, __bb_right + 1)): cells.append((__row, __col, __tab)) cell_set = set(cells) # Loop over those with non-standard attributes for key in cell_set: if key not in code_array and all(ele >= 0 for ele in key): row, col, tab = key style = self._get_xfstyle(worksheets, key) worksheets[tab].write(row, col, label="", style=style)
Updates code in xls code_array
def _xls2code(self, worksheet, tab): """Updates code in xls code_array""" def xlrddate2datetime(xlrd_date): """Returns datetime from xlrd_date""" try: xldate_tuple = xlrd.xldate_as_tuple(xlrd_date, self.workbook.datemode) return datetime(xldate_tuple) except (ValueError, TypeError): return '' type2mapper = { 0: lambda x: None, # Empty cell 1: lambda x: str(x), # Text cell 2: lambda x: str(x), # Number cell 3: xlrddate2datetime, # Date 4: lambda x: str(bool(x)), # Boolean cell 5: lambda x: str(x), # Error cell 6: lambda x: None, # Blank cell } rows, cols = worksheet.nrows, worksheet.ncols for row, col in product(xrange(rows), xrange(cols)): cell_type = worksheet.cell_type(row, col) cell_value = worksheet.cell_value(row, col) key = row, col, tab mapper = type2mapper[cell_type] self.code_array[key] = mapper(cell_value)
Returns xlwt.Font for pyspread style
def _get_font(self, pys_style): """Returns xlwt.Font for pyspread style""" # Return None if there is no font if "textfont" not in pys_style: return font = xlwt.Font() font.name = pys_style["textfont"] if "pointsize" in pys_style: font.height = pys_style["pointsize"] * 20.0 if "fontweight" in pys_style: font.bold = (pys_style["fontweight"] == wx.BOLD) if "fontstyle" in pys_style: font.italic = (pys_style["fontstyle"] == wx.ITALIC) if "textcolor" in pys_style: textcolor = wx.Colour() textcolor.SetRGB(pys_style["textcolor"]) font.colour_index = self.color2idx(*textcolor.Get()) if "underline" in pys_style: font.underline_type = pys_style["underline"] if "strikethrough" in pys_style: font.struck_out = pys_style["strikethrough"] return font
Returns xlwt.Alignment for pyspread style
def _get_alignment(self, pys_style): """Returns xlwt.Alignment for pyspread style""" # Return None if there is no alignment alignment_styles = ["justification", "vertical_align", "angle"] if not any(astyle in pys_style for astyle in alignment_styles): return def angle2xfrotation(angle): """Returns angle from xlrotatation""" # angle is counterclockwise if 0 <= angle <= 90: return angle elif -90 <= angle < 0: return 90 - angle return 0 justification2xfalign = { "left": 1, "center": 2, "right": 3, } vertical_align2xfalign = { "top": 0, "middle": 1, "bottom": 2, } alignment = xlwt.Alignment() try: alignment.horz = justification2xfalign[pys_style["justification"]] except KeyError: pass try: alignment.vert = \ vertical_align2xfalign[pys_style["vertical_align"]] except KeyError: pass try: alignment.rota = angle2xfrotation(pys_style["angle"]) except KeyError: pass return alignment
Returns xlwt.pattern for pyspread style
def _get_pattern(self, pys_style): """Returns xlwt.pattern for pyspread style""" # Return None if there is no bgcolor if "bgcolor" not in pys_style: return pattern = xlwt.Pattern() pattern.pattern = xlwt.Pattern.SOLID_PATTERN bgcolor = wx.Colour() bgcolor.SetRGB(pys_style["bgcolor"]) pattern.pattern_fore_colour = self.color2idx(*bgcolor.Get()) return pattern
Returns xlwt.Borders for pyspread style
def _get_borders(self, pys_style, pys_style_above, pys_style_left): """Returns xlwt.Borders for pyspread style""" # Return None if there is no border key border_keys = [ "borderwidth_right", "borderwidth_bottom", "bordercolor_right", "bordercolor_bottom", ] if not any(border_key in pys_style for border_key in border_keys): return def width2border_line_style(width): if width == 0: return xlwt.Borders.NO_LINE if 0 < width < 2: return xlwt.Borders.THIN if 2 <= width < 6: return xlwt.Borders.MEDIUM if width >= 6: return xlwt.Borders.THICK raise ValueError("Width {} unknown".format(width)) DEFAULT_LINE_STYLE = xlwt.Borders.THIN DEFAULT_COLOR_IDX = 0x16 # Tried out with gnumeric and LibreOffice borders = xlwt.Borders() # Width / style # ------------- # Bottom width try: bottom_pys_style = pys_style["borderwidth_bottom"] bottom_line_style = width2border_line_style(bottom_pys_style) except KeyError: # No or unknown border width bottom_line_style = DEFAULT_LINE_STYLE finally: borders.bottom = bottom_line_style # Right width try: right_pys_style = pys_style["borderwidth_right"] right_line_style = width2border_line_style(right_pys_style) except KeyError: # No or unknown border width right_line_style = DEFAULT_LINE_STYLE finally: borders.right = right_line_style # Top width try: top_pys_style = pys_style_above["borderwidth_bottom"] top_line_style = width2border_line_style(top_pys_style) except KeyError: # No or unknown border width top_line_style = DEFAULT_LINE_STYLE finally: borders.top = top_line_style # Left width try: left_pys_style = pys_style_left["borderwidth_right"] left_line_style = width2border_line_style(left_pys_style) except KeyError: # No or unknown border width left_line_style = DEFAULT_LINE_STYLE finally: borders.left = left_line_style # Border colors # ------------- # Bottom color def _get_color_idx(color): """Converts wx.Colour to Excel color index Differs from self.color2idx because it maps the pyspread default grid color to the Excel default color Parameters ---------- color: wx.Colour \tColor to be converted """ if color == get_color(config["grid_color"]): return DEFAULT_COLOR_IDX else: return self.color2idx(*color.Get()) try: bottom_color_pys_style = pys_style["bordercolor_bottom"] bcolor = wx.Colour() bcolor.SetRGB(bottom_color_pys_style) bottom_color_idx = _get_color_idx(bcolor) except KeyError: # No or unknown border color bottom_color_idx = DEFAULT_COLOR_IDX finally: borders.bottom_colour = bottom_color_idx # Right color try: right_color_pys_style = pys_style["bordercolor_right"] rcolor = wx.Colour() rcolor.SetRGB(right_color_pys_style) right_colour_idx = _get_color_idx(rcolor) except KeyError: # No or unknown border color right_colour_idx = DEFAULT_COLOR_IDX finally: borders.right_colour = right_colour_idx # Top color try: top_color_pys_style = pys_style_above["bordercolor_bottom"] tcolor = wx.Colour() tcolor.SetRGB(top_color_pys_style) top_color_idx = _get_color_idx(tcolor) except KeyError: # No or unknown border color top_color_idx = DEFAULT_COLOR_IDX finally: borders.top_colour = top_color_idx # Left color try: left_color_pys_style = pys_style_left["bordercolor_right"] lcolor = wx.Colour() lcolor.SetRGB(left_color_pys_style) left_colour_idx = _get_color_idx(lcolor) except KeyError: # No or unknown border color left_colour_idx = DEFAULT_COLOR_IDX finally: borders.left_colour = left_colour_idx return borders
Gets XFStyle for cell key
def _get_xfstyle(self, worksheets, key): """Gets XFStyle for cell key""" row, col, tab = key dict_grid = self.code_array.dict_grid dict_grid.cell_attributes._update_table_cache() pys_style = dict_grid.cell_attributes[key] pys_style_above = dict_grid.cell_attributes[row - 1, col, tab] pys_style_left = dict_grid.cell_attributes[row, col - 1, tab] xfstyle = xlwt.XFStyle() # Font # ---- font = self._get_font(pys_style) if font is not None: xfstyle.font = font # Alignment # --------- alignment = self._get_alignment(pys_style) if alignment is not None: xfstyle.alignment = alignment # Background / pattern # -------------------- pattern = self._get_pattern(pys_style) if pattern is not None: xfstyle.pattern = pattern # Border # ------ borders = self._get_borders(pys_style, pys_style_above, pys_style_left) if borders is not None: xfstyle.borders = borders return xfstyle
Appends to cell_attributes with checks
def _cell_attribute_append(self, selection, tab, attributes): """Appends to cell_attributes with checks""" cell_attributes = self.code_array.cell_attributes thick_bottom_cells = [] thick_right_cells = [] # Does any cell in selection.cells have a larger bottom border? if "borderwidth_bottom" in attributes: bwidth = attributes["borderwidth_bottom"] for row, col in selection.cells: __bwidth = cell_attributes[row, col, tab]["borderwidth_bottom"] if __bwidth > bwidth: thick_bottom_cells.append((row, col)) # Does any cell in selection.cells have a larger right border? if "borderwidth_right" in attributes: rwidth = attributes["borderwidth_right"] for row, col in selection.cells: __rwidth = cell_attributes[row, col, tab]["borderwidth_right"] if __rwidth > rwidth: thick_right_cells.append((row, col)) for thick_cell in thick_bottom_cells + thick_right_cells: try: selection.cells.remove(thick_cell) except ValueError: pass cell_attributes.append((selection, tab, attributes)) if thick_bottom_cells: bsel = copy(selection) bsel.cells = thick_bottom_cells battrs = copy(attributes) battrs.pop("borderwidth_bottom") cell_attributes.append((bsel, tab, battrs)) if thick_right_cells: rsel = copy(selection) rsel.cells = thick_right_cells rattrs = copy(attributes) rattrs.pop("borderwidth_right") cell_attributes.append((rsel, tab, rattrs))
Updates attributes in code_array
def _xls2attributes(self, worksheet, tab): """Updates attributes in code_array""" # Merged cells for top, bottom, left, right in worksheet.merged_cells: attrs = {"merge_area": (top, left, bottom - 1, right - 1)} selection = Selection([(top, left)], [(bottom - 1, right - 1)], [], [], []) self.code_array.cell_attributes.append((selection, tab, attrs)) # Which cell comprise which format ids xf2cell = dict((xfid, []) for xfid in xrange(self.workbook.xfcount)) rows, cols = worksheet.nrows, worksheet.ncols for row, col in product(xrange(rows), xrange(cols)): xfid = worksheet.cell_xf_index(row, col) xf2cell[xfid].append((row, col)) for xfid, xf in enumerate(self.workbook.xf_list): selection = Selection([], [], [], [], xf2cell[xfid]) selection_above = selection.shifted(-1, 0) selection_left = selection.shifted(0, -1) attributes = {} # Alignment xfalign2justification = { 0: "left", 1: "left", 2: "center", 3: "right", 4: "left", 5: "left", 6: "center", 7: "left", } xfalign2vertical_align = { 0: "top", 1: "middle", 2: "bottom", 3: "middle", 4: "middle", } def xfrotation2angle(xfrotation): """Returns angle from xlrotatation""" # angle is counterclockwise if 0 <= xfrotation <= 90: return xfrotation elif 90 < xfrotation <= 180: return - (xfrotation - 90) return 0 try: attributes["justification"] = \ xfalign2justification[xf.alignment.hor_align] attributes["vertical_align"] = \ xfalign2vertical_align[xf.alignment.vert_align] attributes["angle"] = \ xfrotation2angle(xf.alignment.rotation) except AttributeError: pass # Background if xf.background.fill_pattern == 1: color_idx = xf.background.pattern_colour_index color = self.idx2colour(color_idx) attributes["bgcolor"] = color.GetRGB() # Border __border_line_style2width = { 0: 1, 1: 1, 2: 4, 5: 7, } def constant_factory(value): return repeat(value).next border_line_style2width = defaultdict(constant_factory(1)) border_line_style2width.update(__border_line_style2width) bottom_color_idx = xf.border.bottom_colour_index if bottom_color_idx in self.workbook.colour_map and \ self.workbook.colour_map[bottom_color_idx] is not None: bottom_color = self.idx2colour(bottom_color_idx) attributes["bordercolor_bottom"] = bottom_color.GetRGB() right_color_idx = xf.border.right_colour_index if right_color_idx in self.workbook.colour_map and \ self.workbook.colour_map[right_color_idx] is not None: right_color = self.idx2colour(right_color_idx) attributes["bordercolor_right"] = right_color.GetRGB() bottom_width = border_line_style2width[xf.border.bottom_line_style] attributes["borderwidth_bottom"] = bottom_width right_width = border_line_style2width[xf.border.right_line_style] attributes["borderwidth_right"] = right_width # Font font = self.workbook.font_list[xf.font_index] attributes["textfont"] = font.name attributes["pointsize"] = font.height / 20.0 fontweight = wx.BOLD if font.weight == 700 else wx.NORMAL attributes["fontweight"] = fontweight if font.italic: attributes["fontstyle"] = wx.ITALIC if font.colour_index in self.workbook.colour_map and \ self.workbook.colour_map[font.colour_index] is not None: attributes["textcolor"] = \ self.idx2colour(font.colour_index).GetRGB() if font.underline_type: attributes["underline"] = True if font.struck_out: attributes["strikethrough"] = True # Handle top cells' top borders attributes_above = {} top_width = border_line_style2width[xf.border.top_line_style] if top_width != 1: attributes_above["borderwidth_bottom"] = top_width top_color_idx = xf.border.top_colour_index if top_color_idx in self.workbook.colour_map and \ self.workbook.colour_map[top_color_idx] is not None: top_color = self.idx2colour(top_color_idx) attributes_above["bordercolor_bottom"] = top_color.GetRGB() # Handle leftmost cells' left borders attributes_left = {} left_width = border_line_style2width[xf.border.left_line_style] if left_width != 1: attributes_left["borderwidth_right"] = left_width left_color_idx = xf.border.left_colour_index if left_color_idx in self.workbook.colour_map and \ self.workbook.colour_map[left_color_idx] is not None: left_color = self.idx2colour(left_color_idx) attributes_above["bordercolor_right"] = left_color.GetRGB() if attributes_above: self._cell_attribute_append(selection_above, tab, attributes_above) if attributes_left: self._cell_attribute_append(selection_left, tab, attributes_left) if attributes: self._cell_attribute_append(selection, tab, attributes)
Writes row_heights to xls file Format: <row>\t<tab>\t<value>\n
def _row_heights2xls(self, worksheets): """Writes row_heights to xls file Format: <row>\t<tab>\t<value>\n """ xls_max_rows, xls_max_tabs = self.xls_max_rows, self.xls_max_tabs dict_grid = self.code_array.dict_grid for row, tab in dict_grid.row_heights: if row < xls_max_rows and tab < xls_max_tabs: height_pixels = dict_grid.row_heights[(row, tab)] height_inches = height_pixels / float(get_dpi()[1]) height_points = height_inches * 72.0 worksheets[tab].row(row).height_mismatch = True worksheets[tab].row(row).height = int(height_points * 20.0)
Updates row_heights in code_array
def _xls2row_heights(self, worksheet, tab): """Updates row_heights in code_array""" for row in xrange(worksheet.nrows): try: height_points = worksheet.rowinfo_map[row].height / 20.0 height_inches = height_points / 72.0 height_pixels = height_inches * get_dpi()[1] self.code_array.row_heights[row, tab] = height_pixels except KeyError: pass
Returns xls width from given pyspread width
def pys_width2xls_width(self, pys_width): """Returns xls width from given pyspread width""" width_0 = get_default_text_extent("0")[0] # Scale relative to 12 point font instead of 10 point width_0_char = pys_width * 1.2 / width_0 return int(width_0_char * 256.0)
Writes col_widths to xls file Format: <col>\t<tab>\t<value>\n
def _col_widths2xls(self, worksheets): """Writes col_widths to xls file Format: <col>\t<tab>\t<value>\n """ xls_max_cols, xls_max_tabs = self.xls_max_cols, self.xls_max_tabs dict_grid = self.code_array.dict_grid for col, tab in dict_grid.col_widths: if col < xls_max_cols and tab < xls_max_tabs: pys_width = dict_grid.col_widths[(col, tab)] xls_width = self.pys_width2xls_width(pys_width) worksheets[tab].col(col).width = xls_width
Updates col_widths in code_array
def _xls2col_widths(self, worksheet, tab): """Updates col_widths in code_array""" for col in xrange(worksheet.ncols): try: xls_width = worksheet.colinfo_map[col].width pys_width = self.xls_width2pys_width(xls_width) self.code_array.col_widths[col, tab] = pys_width except KeyError: pass