sopen

sopen


License
MIT
Install
pip install sopen==0.0.3

Documentation

The sopen Package

What is sopen?

sopen is a simple Python2 and Python3-compatible package which wraps Python's Popen. sopen strives to be a cross-platform library available in both Linux and Windows.

sopen runs a shell command in one of two ways:

  • 'blocking' mode, which blocks until the shell command finishes.
  • 'nonblocking' mode, which enables the user to see output from the command as it runs.

The primary goal of sopen is simplicity. The user doesn't need to think about pipes, queues, threading, or any of the other issues that come up while using Popen (especially in nonblocking use cases).

As with anything, simplicity comes with tradeoffs:

  • At this time, sopen does not support piping commands into other process (or piping commands through the shell). Use Popen if piping commands into each other is required
  • Usage of 'blocking' and 'nonblocking' modes are different.

Blocking mode usage

This captures the output of a grep and prints it to stdout...

from sopen import Sopen

# This blocks until the output of the grep finishes...
proc = Sopen('grep foo bar.txt', mode='blocking')

for line in proc.stdout.read().splitlines():
    print(line)

Non-blocking mode usage

Non-blocking mode is best for commands that stream output non-stop, or processes that you may want to react to in real-time. This example captures the output of a ping command (five pings) and prints it to stdout...

from sopen import Sopen

ping_addrs = '127.0.0.1'

proc = Sopen('ping -c 5 -O {0}'.format(ping_addrs), mode='nonblocking')

finished = False
while not finished:

    # readline_stdout() is only available in nonblocking mode
    # The timeout parameter tells sopen how long to wait for output;
    #    if there is no output before the timeout, None is returned.
    out = proc.readline_stdout(timeout=0.001)
    err = proc.readline_stderr(timeout=0.001)
    if (out is not None):
        print("{}".format(out))
    if (err is not None):
        print("ERROR {}".format(err))

    if proc.stdout_done and proc.stderr_done:
        finished = True

Where sopen really shines is when you need to spawn many streaming shell commands and monitor them all at once.

The following example pings four addresses simultaneously and prints output for them all.

from sopen import Sopen

ping_addrs = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4']
procs = dict()

# Spawn pings for all addresses
for addr in ping_addrs:
    proc = Sopen('ping -A -O {0}'.format(addr), mode='nonblocking')
    procs[addr] = proc

while True:
    for addr, proc in procs.items():
        out = proc.readline_stdout(timeout=0.001)
        err = proc.readline_stderr(timeout=0.001)
        if (out is not None):
            print("{}".format(out))
        if (err is not None):
            print("ERROR {}".format(err))