Package: clibroker
PyCliBrokerCommand-line interface I/O broker with sessions for asynchronous applications.CliBroker provides an asynchronous interface to synchronize stdio read/write commands by FIFO. Sessions allow grouping
such commands together, suspending calls outside of such a session until the active session has terminated. These
sessions can also be nested.CliBroker processes each request one after another in a single separate thread. CliBroker will properly handle cancellation
of requests.Table of ContentsPyCliBrokerTable of ContentsInstallationUsageSessionsasyncSession.read(n: int) -> strasyncSession.readline() -> strasyncSession.password(prompt: str = 'Password: ') -> strasyncSession.write(*data, sep: str = ' ', err: bool = False, flush: Optional[bool] = None)asyncSession.writeline(*data, sep: str = ' ', err: bool = False, flush: Optional[bool] = None)asyncSession.flush(flush_stdout: bool = True, flush_stderr: bool = True) -> NoneasyncSession.standby() -> strasyncSession.session(autoflush: Optional[bool] = None) -> SessionTechnical DetailsBackground ThreadGlobal SessionFurther TestingLicenseInstallationSimply install viapip install clibroker.UsageCliBroker exposes a familiar IO-like interface. A simple example usage is as follows:importasyncioimportclibrokerascliasyncdefmain():cli.writeline('Hello, world!')t1=asyncio.create_task(async1())t2=asyncio.create_task(async2())awaitt1;awaitt2# > Hello, world!# > Say something: <input:"test 123"># > Thanks for those 9 characters.# > Fooasyncdefasync1():awaitasyncio.sleep(0.1)awaitcli.writeline('Foo')asyncdefasync2():asyncwithcli.session(autoflush=True)assess:awaitsess.write('Say something: ')input=awaitsess.readline()iflen(input)>0:awaitsess.writeline(f'Thanks for those{len(input)}characters.')else:awaitsess.writeline('Okay, then not.')if__name__=='__main__':asyncio.run(main())SessionsAs mentioned above,clibroker.sessionis probably the most useful feature of this library. As the output of the code
above demonstrates, it allows "grouping" CLI commands together and to postpone any other intermittent call until this
session is closed.CliBroker uses an implicit "global session" to expose specific top-level functions for CLI commands without an associated
session:read,readline,write,writeline,password, andsession. Their default behavior in the global
session is documented in their respective sections below.asyncSession.read(n: int) -> strRead at mostncharacters from stdin.asyncSession.readline() -> strRead an entire line from stdin (up until and including the '\n' character).asyncSession.password(prompt: str = 'Password: ') -> strRead a password from stdin similar to Unix-style applications with an optionalprompt. User input will not be echoed
to stdout.Caveat: It is possible to rebind output and input streams that a session uses - howeverSession.passwordwill always
usesys.stdinandsys.stdout(for the prompt). On one hand, this is a limitation of the standard librarygetpass. On the other hand, support for other streams is typically
not needed are likely not mandatorily linked to a console.asyncSession.write(*data, sep: str = ' ', err: bool = False, flush: Optional[bool] = None)Write alldatastringified and joined bysep.Iferris false, data is written to stdout, else to stderr.flushdictates whether to immediately flush the output.Ifflushis true, output is immediately flushed.Ifflushis false, obviously it is not flushed.Ifflush is None, resorts to associated session's default autoflush behavior.Global session's autoflush behavior is true.asyncSession.writeline(*data, sep: str = ' ', err: bool = False, flush: Optional[bool] = None)Same asSession.write, except appends a newline character ('\n') to the data.asyncSession.flush(flush_stdout: bool = True, flush_stderr: bool = True) -> NoneExplicitly flush stdout and/or stderr.This method is not exposed as top-level function of the global session as the global session always automatically flushes.asyncSession.standby() -> strA specialSession.readlinewhich lurks to intercept user input while no other read command (Session.readorSession.readline) is pending. If a read command is issued or a session opened, standby will be postponed until all
requests are completed first.asyncSession.session(autoflush: Optional[bool] = None) -> SessionCreates a new subsession. All subsequent CLI commands on this session will be postponed until this subsession is concluded.autoflushdetermines the new session's default autoflushing behavior as used bySession.writeandSession.writelinemethods:True: Automatically flush.False: Do not automatically flush.None: Adopt parent session's current autoflush behavior.The global session by default usesautoflush=False.Technical DetailsBeware of backpressure!CliBroker buffers every single request internally in order to achieve predictability.
Backpressure may build up when quickly and regularly queuing requests without ever synchronizing, most noticably with
read requests.Background ThreadAs mentioned before, CliBroker employs a single background thread to process its queue of requests. In order to avoid
regular termination this background thread is terminated upon completion of all requests. However, as this may lead to
a considerable thread creation overhead, CliBroker waits for new requests for at most 10ms before terminating - a time
span short enough to be barely noticeable but long enough to avoid unnecessary thread creation for most common tasks.Global SessionThe global session is simply aSessionwhose methods (partly with altered default behavior) are exposed as top-level
bound functions.The global session can be accessed and changed viaclibroker.clibroker._sessionto further alter its default behavior
(such as changing I/O streams). This interface may be useful to the advanced user. It was developed for the purposes of
unit testing and is not intended as part of the public interface.Further TestingCliBroker was developed as part of my hobby project. Currently, I am its sole developer and maintainer. Naturally, I do
not have extensive time to invest into the development of this project. I have set up unit tests for various cases, but
these by far do not provide sufficient coverage.The following points probably need more testing:Multithreaded use - theoretically supported but untestedRequest cancellationstandbyfeaturePython version - I'm not entirely sure what the oldest supported Python version is (3.6?)LicenseMIT LicenseCopyright (c) 2021 KirusePermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.