twain – main module¶
- class twain.Source(sm: SourceManager, ds_id: TW_IDENTITY)[source]¶
Bases:
object
This object represents connection to Data Source.
An instance of this class can be created by calling
SourceManager.open_source()
- acquire_file(before: ~collections.abc.Callable[[dict], str], after: ~collections.abc.Callable[[int], None] = <function Source.<lambda>>, show_ui: bool = True, modal: bool = False) None [source]¶
Acquires one or more images as files. Call returns when acquisition complete.
- Parameters:
before – Callback called before each acquired file, it should return full file path to where image should be saved. It can also throw CancelAll to cancel acquisition
after – Callback called after each acquired file, it receives number of images remaining. It can throw CancelAll to cancel remaining acquisition
show_ui – If True source’s UI will be presented to user
modal – If True source’s UI will be modal
- acquire_natively(after: ~collections.abc.Callable[[~twain._IImage, int], None], before: ~collections.abc.Callable[[dict], None] = <function Source.<lambda>>, show_ui: bool = True, modal: bool = False) None [source]¶
Acquires one or more images via memory. Call returns when acquisition complete.
This function will run its own event loop while it is executing.
- Parameters:
after – Callback called after each acquired file, it receives an image object and number of images remaining. It can throw CancelAll to cancel remaining acquisition
before – Callback called before each acquired file. It can throw CancelAll to cancel acquisition
show_ui – If True source’s UI will be presented to user
modal – If True source’s UI will be modal
- close()[source]¶
This method is used to close the data source object. It gives finer control over this connects than relying on garbage collection.
- property file_xfer_params: tuple[str, int]¶
Property which stores tuple of (file name, format) where format is one of TWFF_*
This property is used by
xfer_image_by_file()
Valid states: 4, 5, 6
- get_capability(cap: int)[source]¶
This function is used to return the capability information from the source. If the capability is not supported, an exception should be returned. Capabilities are returned as a tuple of a type (TWTY_*) and a value. The format of values depends on their container type. Capabilities can be in any of the following containers:
singleton, range, enumerator or array.
singletons are returned as a single value (integer or string) ranges are returned as a tuple dictionary containing MinValue,
MaxValue, StepSize, DefaultValue and CurrentValue
- enumerators and arrays are returned as tuples, each containing
a list which has the actual values
- get_capability_current(cap: int)[source]¶
This function is used to return the current value of a capability from the source. If the capability is not supported, an exception should be returned. Capabilities are returned as a tuple of a type (TWTY_*) and a value. The format of values depends on their container type. Capabilities can be in any of the following containers:
singleton, range, enumerator or array.
singletons are returned as a single value (integer or string) ranges are returned as a tuple dictionary containing MinValue,
MaxValue, StepSize, DefaultValue and CurrentValue
- enumerators and arrays are returned as tuples, each containing
a list which has the actual values
- get_capability_default(cap: int)[source]¶
This function is used to return the default value of a capability from the source. If the capability is not supported, an exception should be returned. Capabilities are returned as a tuple of a type (TWTY_*) and a value. The format of values depends on their container type. Capabilities can be in any of the following containers:
singleton, range, enumerator or array.
singletons are returned as a single value (integer or string) ranges are returned as a tuple dictionary containing MinValue,
MaxValue, StepSize, DefaultValue and CurrentValue
- enumerators and arrays are returned as tuples, each containing
a list which has the actual values
- get_image_layout() tuple[tuple[float, float, float, float], int, int, int] [source]¶
This function is used to ask the source for Image Layout.
It returns a tuple containing frame coordinates, document number, page number, frame number.
Valid states 4 through 6
- get_image_layout_default() tuple[tuple[float, float, float, float], int, int, int] [source]¶
This function is used to ask the source for default Image Layout.
It returns a tuple containing frame coordinates, document number, page number, frame number.
Valid states 4 through 6
- hide_ui() None [source]¶
This function is used to ask the source to hide the user interface.
Transitions Source to state 4 if successful.
Valid states: 5
- property identity: dict¶
This function is used to retrieve information about the source. driver. The information is returned in a dictionary.
- property image_info: dict¶
This function is used to ask the source for Image Info. Normally, the application is notified that the image is ready for transfer using the message loop. However, it is hard to get at the message loop in toolkits such as wxPython. As an alternative, I poll the source looking for image information. When the image information is available, the image is ready for transfer
Valid states: 6, 7
- modal_loop() None [source]¶
This function should be called after call to
requiest_acquire()
it will return after acquisition complete.Valid states: 5
- property name: str¶
Get the name of the source. This can be used later for connecting to the same source.
- request_acquire(show_ui: bool, modal_ui: bool) None [source]¶
This function is used to ask the source to begin acquisition.
Transitions Source to state 5.
- Parameters:
show_ui – bool (default 1)
modal_ui – bool (default 1)
Valid states: 4
- reset_capability(cap: int)[source]¶
This function is used to reset the value of a capability to the source default.
- Parameters:
cap – Capability Identifier (lowlevel.CAP_* or lowlevel.ICAP_*).
- set_capability(cap: int, type_id: int, value: int | float | str | tuple[float, float, float, float])[source]¶
This function is used to set the value of a capability in the source. Three parameters are required, a Capability Identifier (lowlevel.CAP_* or lowlevel.ICAP_*) a value type (lowlevel.TWTY_*) and a value If the capability is not supported, an exception should be returned. This function is used to set a value using a TW_ONEVALUE.
- set_image_layout(frame: tuple[float, float, float, float], document_number: int = 1, page_number: int = 1, frame_number: int = 1)[source]¶
This function is used to inform the source of the Image Layout.
It uses a tuple containing frame coordinates, document number, page number, frame number.
- xfer_image_by_file() int [source]¶
Perform a file based transfer of the image.
When successful, the file is saved to the image file, defined in a previous call to
file_xfer_params()
.Returns the number of pending transfers
If remaining number of images is zero Source will transition to state 5, otherwise it stays in state 6 in which case you should call
xfer_image_natively()
again.Valid states: 6
- xfer_image_natively() tuple[Any, int] [source]¶
Perform a ‘Native’ form transfer of the image.
When successful, this routine returns two values, an image handle and a count of the number of images remaining in the source.
If remaining number of images is zero Source will transition to state 5, otherwise it stays in state 6 in which case you should call
xfer_image_natively()
again.Valid states: 6
- class twain.SourceManager(parent_window=None, MajorNum: int = 1, MinorNum: int = 0, Language: int = 13, Country: int = 1, Info: str = '', ProductName: str = 'TWAIN Python Interface', ProtocolMajor: Literal[1, 2] | None = None, ProtocolMinor: int | None = None, SupportedGroups: int = 3, Manufacturer: str = 'pytwain', ProductFamily: str = 'TWAIN Python Interface', dsm_name: str | None = None)[source]¶
Bases:
object
Represents a Data Source Manager connection.
This is the first class that you need to create.
From instance of this class you can list existing sources using
source_list()
property.You can open source using
open_source()
method and then use methods on the returned object to perform scanning.When done call
close()
method to release resources.- close() None [source]¶
This method is used to force the SourceManager to close down. It is provided for finer control than letting garbage collection drop the connections.
- property identity: dict¶
This property is used to retrieve the identity of our application. The information is returned in a dictionary.
- open_source(product_name: str | None = None) Source | None [source]¶
Open a TWAIN Source.
If product_name parameter is specified, will open source matching that product name. Otherwise, will present a source selection dialog box to user. Once user selects a source, that source will be opened.
Returns a
Source
object, which can be used to communicate with the source or None if user cancelled source selection dialog.- Parameters:
product_name – source to be opened, if not specified or value is None user will be prompted for source selection
- set_callback(cb: Callable[[int], None] | None)[source]¶
Register a python function to be used for notification that the transfer is ready, etc.
- property source_list: list[str]¶
Returns a list containing the names of available sources
- twain.acquire(path: str, ds_name: str | None = None, dpi: float | None = None, pixel_type: Literal['bw', 'gray', 'color'] | None = None, bpp: int | None = None, frame: tuple[float, float, float, float] | None = None, parent_window=None, show_ui: bool = False, dsm_name: str | None = None, modal: bool = False) dict | None [source]¶
Acquires single image into file
- Parameters:
path – Path where to save image
ds_name – name of lowlevel data source, if not provided user will be presented with selection dialog
dpi – resolution in dots per inch
pixel_type – can be ‘bw’, ‘gray’, ‘color’
bpp – bits per pixel
frame – tuple (left, top, right, bottom) scan area in inches
parent_window – can be Tk, Wx, Gtk window object or Win32 window handle
show_ui – if True source’s UI dialog will be presented to user
dsm_name – optional name or path for TWAIN Data Source Manager DLL
modal – whether to use modal dialog for scanner UI
Returns a dictionary describing image, or None if scanning was cancelled by user
twain.exceptions – Exception classes¶
- exception twain.exceptions.BadCapability[source]¶
Bases:
TwainError
Source does not support specified capability. Sources newer than 1.6 do not use report this error.
- exception twain.exceptions.BadDestination[source]¶
Bases:
TwainError
Operation was sent to invalid Source
- exception twain.exceptions.BadProtocol[source]¶
Bases:
TwainError
Operation is not recognized by Source
- exception twain.exceptions.CancelAll[source]¶
Bases:
Exception
Exception used by callbacks to cancel remaining image transfers
- exception twain.exceptions.CapBadOperation[source]¶
Bases:
TwainError
Operation (i.e., Get or Set) not supported on capability.
- exception twain.exceptions.CapSeqError[source]¶
Bases:
TwainError
Capability has dependencies on other capabilities and cannot be operated upon at this time.
- exception twain.exceptions.CapUnsupported[source]¶
Bases:
TwainError
Capability not supported by Source. Sources with version 1.6 and newer use this error instead of BadCapability error
- exception twain.exceptions.CapabilityFormatNotSupported[source]¶
Bases:
TwainError
Specified capability is not supported by pytwain
- exception twain.exceptions.CheckDeviceOnlineError[source]¶
Bases:
TwainError
Check the device status using CAP_DEVICEONLINE, this condition code can be returned by any TWAIN operation in state 4 or higher, or from the state 3 DG_CONTROL / DAT_IDENTITY / MSG_OPENDS. The state remains unchanged. If in state 4 the Application can poll with CAP_DEVICELINE until the value returns TRUE.
- exception twain.exceptions.CheckStatus[source]¶
Bases:
Exception
This exception means that operation succeeded but user value was truncated to fit valid range
- exception twain.exceptions.DSTransferCancelled[source]¶
Bases:
TwainError
Data transfer was cancelled by user
- exception twain.exceptions.DeniedError[source]¶
Bases:
TwainError
Operation denied
- exception twain.exceptions.FileWriteError[source]¶
Bases:
TwainError
Operation failed writing to the file.
- exception twain.exceptions.GeneralFailure[source]¶
Bases:
TwainError
General failure. Unload Source immediately.
- exception twain.exceptions.ImageFormatNotSupported[source]¶
Bases:
TwainError
Image has unsupported format. E.g. compressed images are not supported currently.
- exception twain.exceptions.MaxConnectionsError[source]¶
Bases:
TwainError
Device is connected to maximum number of applications it can support.
- exception twain.exceptions.NoDataSourceError[source]¶
Bases:
TwainError
No Source found
- exception twain.exceptions.NotEmptyError[source]¶
Bases:
TwainError
Directory not empty and cannot be deleted
- exception twain.exceptions.OperationError[source]¶
Bases:
TwainError
Internal Source error
- exception twain.exceptions.PaperDoubleFeedError[source]¶
Bases:
TwainError
Feeder error. This error is obsolete but may still be reported by older sources.
- exception twain.exceptions.PaperJam[source]¶
Bases:
TwainError
Paper got stuck in feeder
- exception twain.exceptions.SMGetProcAddressFailed[source]¶
Bases:
TwainError
Specified driver does not have DSM_Entry symbol defined
- exception twain.exceptions.SMLoadFileFailed[source]¶
Bases:
TwainError
Failed to load DLL
- exception twain.exceptions.SMOpenFailed[source]¶
Bases:
TwainError
DSM entry point returned error when called.
- exception twain.exceptions.SequenceError[source]¶
Bases:
TwainError
Operation was called at a wrong state
- exception twain.exceptions.TwainError[source]¶
Bases:
Exception
Base error for all errors returned by TWAIN driver
- exception twain.exceptions.UnknownError[source]¶
Bases:
TwainError
Unknown error code was returned. Probably need to upgrade pytds to newer version.
- twain.exceptions.excCapabilityFormatNotSupported¶
alias of
CapabilityFormatNotSupported
- twain.exceptions.excDSTransferCancelled¶
alias of
DSTransferCancelled
- twain.exceptions.excImageFormat¶
alias of
ImageFormatNotSupported
- twain.exceptions.excSMGetProcAddressFailed¶
alias of
SMGetProcAddressFailed
- twain.exceptions.excSMLoadFileFailed¶
alias of
SMLoadFileFailed
- twain.exceptions.excSMOpenFailed¶
alias of
SMOpenFailed
- twain.exceptions.excTWCC_BADCAP¶
alias of
BadCapability
- twain.exceptions.excTWCC_BADDEST¶
alias of
BadDestination
- twain.exceptions.excTWCC_BADPROTOCOL¶
alias of
BadProtocol
- twain.exceptions.excTWCC_BUMMER¶
alias of
GeneralFailure
- twain.exceptions.excTWCC_CAPBADOPERATION¶
alias of
CapBadOperation
- twain.exceptions.excTWCC_CAPSEQERROR¶
alias of
CapSeqError
- twain.exceptions.excTWCC_CAPUNSUPPORTED¶
alias of
CapUnsupported
- twain.exceptions.excTWCC_CHECKDEVICEONLINE¶
alias of
CheckDeviceOnlineError
- twain.exceptions.excTWCC_DENIED¶
alias of
DeniedError
- twain.exceptions.excTWCC_FILEWRITEERROR¶
alias of
FileWriteError
- twain.exceptions.excTWCC_MAXCONNECTIONS¶
alias of
MaxConnectionsError
- twain.exceptions.excTWCC_NODS¶
alias of
NoDataSourceError
- twain.exceptions.excTWCC_NOTEMPTY¶
alias of
NotEmptyError
- twain.exceptions.excTWCC_OPERATIONERROR¶
alias of
OperationError
- twain.exceptions.excTWCC_PAPERDOUBLEFEED¶
alias of
PaperDoubleFeedError
- twain.exceptions.excTWCC_SEQERROR¶
alias of
SequenceError
- twain.exceptions.excTWCC_UNKNOWN¶
alias of
UnknownError
twain.windows – Windows platform bindings¶
- twain.windows.DIBToBMFile(handle, path=None)[source]¶
Backward compatible alias for
dib_to_bm_file()
- twain.windows.DIBToXBMFile(handle, path=None)[source]¶
Backward compatible alias for
dib_to_xbm_file()
- twain.windows.GlobalHandleAllocate(flags, size)[source]¶
Backward compatible alias for
global_handle_allocate()
- twain.windows.GlobalHandleFree(handle)[source]¶
Backward compatible alias for
global_handle_free()
- twain.windows.GlobalHandleGetBytes(handle, offset, count)[source]¶
Backward compatible alias for
global_handle_get_bytes()
- twain.windows.GlobalHandlePutBytes(handle, offset, count, data)[source]¶
Backward compatible alias for
global_handle_put_bytes()
- twain.windows.dib_to_bm_file(handle, path: str | None = None) bytes | None [source]¶
Convert a DIB (Device Independent Bitmap) to a windows bitmap file format. The BitMap file is either returned as a string, or written to a file with the name given in the second argument.
Note
Can only be used with lowlevel 1.x sources
- twain.windows.dib_to_xbm_file(handle, path: str | None = None)[source]¶
Convert a DIB (Device Independent Bitmap) to an X-Windows bitmap file (XBM format). The XBM file is either returned as a string, or written to a file with the name given in the third argument. Parameters:
- Parameters:
handle – Handle to a global area containing a DIB,
path – Path prefix to be used for the name and an optional filename for file only output.
Note
Can only be used with lowlevel 1.x sources
- twain.windows.global_handle_allocate(flags: int, size: int)[source]¶
Allocate a specified number of bytes via a global handle.
Parameters:
- Parameters:
size – The number of bytes to be allocated
Note
Can only be used with lowlevel 1.x sources
- twain.windows.global_handle_free(handle)[source]¶
Free an allocated heap section via the global handle.
Parameters:
- Parameters:
handle – Handle to memory to be freed
Note
Can only be used with lowlevel 1.x sources
- twain.windows.global_handle_get_bytes(handle, offset: int, count: int) bytes [source]¶
Read a specified number of bytes from a global handle.
Parameters: :param handle: Global handle :param offset: An index into the handle data :param count: The number of bytes to be returned
Note
Can only be used with lowlevel 1.x sources
- twain.windows.global_handle_put_bytes(handle, offset: int, count: int, data: bytes)[source]¶
Write a specified number of bytes to a global handle.
Parameters:
- Parameters:
handle – Global handle
offset – An index into the handle data
count – The number of bytes to update
data – String of data to be written
Note
Can only be used with lowlevel 1.x sources