stdopen package

Overide the open method to provide a file-like object or STDIN/STDOUT. Also, provide writing via a temp file if needed. The open function is available from the root i.e. stdin.open.

stdopen.stdopen.get_tmp_file(**kwargs)

Initialise a temp file to work with. This differs from tempfile.mkstemp as the temp file is closed and only the file name is returned.

Parameters

**kwargs – Any arguments usually passed to tempfile.mkstemp

Returns

temp_file_name – The name of a temp file that has been created with the requested parameters.

Return type

str

stdopen.stdopen.has_binary(mode)

Does the mode have binary flag b.

Parameters

mode (str) – The mode string

Returns

has_flagTrue if it contains the flag False if not.

Return type

bool

stdopen.stdopen.has_read(mode)

Does the mode have read flag r.

Parameters

mode (str) – The mode string

Returns

has_flagTrue if it contains the flag False if not.

Return type

bool

stdopen.stdopen.has_write(mode)

Does the mode have write flag w or a.

Parameters

mode (str) – The mode string

Returns

has_flagTrue if it contains the flag False if not.

Return type

bool

stdopen.stdopen.is_std(filename)

Id the filename consistant with wanting input from stdin, stdout or stderr.

Parameters

filename (sys.stdin or sys.stdout or str or NoneType) – If sys.stdin or sys.stdout, NoneType, '-' or '' then it is.

Returns

has_std_flagTrue if it contains the flag False if not.

Return type

bool

stdopen.stdopen.open(filename, mode='rt', method=<built-in function open>, use_tmp=False, tmpdir=None, keep_tmp=False, **kwargs)

Provide either an opened file or STDIN/STDOUT if filename is not a file. This must be used as a context manager.

Parameters
  • filename (str or NoneType) – The filename to open. If -, '' or NoneType then either sys.stdin or sys.stdout is yielded (depending on mode). Otherwise the file is opened with method.

  • mode (str optional, default: rt) – Should be the usual w/wt/wb/r/rt/rb. A '' is interpreted as read as is NoneType.

  • method (function, optional, default: builtins.open) – The open method to use if filename is not using STDIN or STDOUT.

  • use_temp (bool, optional, default: False) – Use a temp file for writing instead of the output file. Then move the temp file to the output file location upon successful closing, or delete if there is an error (unless keep_tmp is True.

  • tmpdir (str or NoneType, optional, default: NoneType) – The location to write any temp files, if NoneType then it defaults to the system temp

  • keep_tmp (bool, optional, default: False) – If the contextmanager exits with an error then do not delete the temp file after closing (might be useful for debugging - if you can id the file).

  • **kwargs – Any other kwargs passed to method.

Yields

fobj (File or sys.stdin or sys.stdout) – A place to read or write depending on filename and mode

Raises

ValueError – If the mode can’t be identified.