Pyjo.IOLoop.ChildProcess - Non-blocking child process

from Pyjo.IOLoop.ChildProcess import ChildProcess

child = ChildProcess()
child.spawn(['ls', '-l'])

# Or import the module, as in Google Python Style Guide

import Pyjo.IOLoop.ChildProcess

# Run a program, with its output and its exit status
child = Pyjo.IOLoop.ChildProcess.new()
child.on('spawn', lambda child: child.stdout.on('read', lambda stream, chunk: print(chunk)))
child.on('close', lambda child, code, signal: print(f'Exited with {code}'))
child.on('error', lambda child, err: print(f"Can't run: {err}"))
child.spawn(['ls', '-l'])

# Write to its standard input, and end it
child = Pyjo.IOLoop.ChildProcess.new().spawn(['sort'])
child.stdout.on('read', lambda stream, chunk: print(chunk))
child.stdin.write(b'b\na\n')
child.stdin.close_gracefully()

# Its output as a promise, also in a coroutine
child = Pyjo.IOLoop.ChildProcess.new()
child.run_p(['ls', '-l']).then(lambda code, out, err: print(out))

# Start reactor if necessary
if not child.reactor.is_running:
    child.reactor.start()

Pyjo.IOLoop.ChildProcess runs a program in a process of its own, as CGI programs and command line tools are, with its standard input, output and error as pipes that the reactor watches, as Pyjo.IOLoop.Stream objects, without blocking the event loop. It runs the program, not a function of Python, as Pyjo.IOLoop.Subprocess does in a fork of the process.

The process is reaped by the reactor, which checks for its end with a timer, and at once when its output and its error have ended, as most programs end them when they exit. The end of the interpreter kills and reaps the processes that are left, and closes their pipes.

The child of a fork leaves the processes of its parent to it: it closes its copies of their pipes, and neither reaps them nor emits their events, which the parent does.

The reactor watches pipes on POSIX systems, not on Windows, where spawn() emits the event error.

Events

Pyjo.IOLoop.ChildProcess inherits all events from Pyjo.EventEmitter and can emit the following new ones.

close

child.on('close', lambda child, code, signal: ...)

Emitted once the process has exited and its output and its error have ended, with its exit code, or the signal that terminated it, after the event exit.

child.on('close', lambda child, code, signal: print(f'Process {child.pid} closed with {code}'))

error

child.on('error', lambda child, err: ...)

Emitted if the program could not be run, as one that does not exist.

child.on('error', lambda child, err: print(f'Error: {err}'))

exit

child.on('exit', lambda child, code, signal: ...)

Emitted once the process has exited, with its exit code, or None and the signal that terminated it. Its output and its error may not have ended yet.

child.on('exit', lambda child, code, signal: print(f'Process {child.pid} exited with {code}'))

spawn

child.on('spawn', lambda child: ...)

Emitted once the process has been spawned, before its output and its error are read, so that the subscribers of this event get all of them.

child.on('spawn', lambda child: print(f'Running process {child.pid}'))

See also

Pyjoyment, https://mojolicious.org.

Inspired by child_process of Node.js, as Mojolicious runs no programs in its event loop.

Classes

class Pyjo.IOLoop.ChildProcess.Pyjo_IOLoop_ChildProcess(*, reactor: Pyjo_Reactor | None = None)[source]

Pyjo.IOLoop.ChildProcess inherits all methods from Pyjo.EventEmitter and implements the following new ones.

property exit_code: int | None[source]
code = child.exit_code

Exit code of the process, or None if it is still running or a signal terminated it.

kill(signal: int = Signals.SIGTERM) → bool[source]
boolean = child.kill()
boolean = child.kill(signal.SIGKILL)

Send a signal to the process, SIGTERM by default, if it is still running, or to the processes of its group, which it may have started, when it has been spawned detached, while any of them runs.

property pid: int | None[source]
pid = child.pid

Process id of the spawned process if available.

property reactor: Pyjo_Reactor[source]
reactor = child.reactor
child.reactor = Pyjo.Reactor.Poll.new()

Low-level event reactor, defaults to the reactor attribute value of the global Pyjo.IOLoop singleton. Note that this attribute is weakened.

run_p(args: Sequence[str | bytes | PathLike[str]], *, input: bytes = b'', **options: Any) → Any[source]
promise = child.run_p(['ls', '-l'])
promise = child.run_p(['sort'], input=b'b\na\n', cwd='/tmp')

Same as spawn(), with the options of spawn(), but writes input to the standard input of the process and ends it, and returns a Pyjo.Promise object, which is fulfilled with the exit code, None for a signal, and the whole output and error of the process as Pyjo.String.Bytes objects once it closes, or rejected if the program could not be run.

# The output of a program in a coroutine
code, out, err = await Pyjo.IOLoop.ChildProcess.new().run_p(['git', 'log', '-1'])
property signal_code: int | None[source]
signal = child.signal_code

Signal that terminated the process, or None.

spawn(args: Sequence[str | bytes | PathLike[str]], *, cwd: str | bytes | PathLike[str] | None = None, detached: bool = False, env: Mapping[str, str] | Mapping[bytes, bytes] | None = None) → Self[source]
child = child.spawn(['ls', '-l'])
child = child.spawn(['php-cgi', 'index.php'], cwd='/var/www', env={'REDIRECT_STATUS': '200'})
child = child.spawn(['make', 'all'], detached=True)

Run a program, the first of args, with the others as its arguments, in the directory cwd and with the environment env, the ones of this process by default. With detached, the process runs in a session of its own, as the leader of a process group, as detached of Node.js, so that kill() signals the processes that it starts too, and a signal of the terminal of this process, as of Ctrl-C, does not reach it. The events spawn or error are emitted in the next tick of the reactor, so that the ones that are subscribed after the call get them too, and the output and the error are read from the event spawn on.

property stderr: Pyjo_IOLoop_Stream | None[source]
stream = child.stderr

Pyjo.IOLoop.Stream object of the standard error of the process, which the reactor reads without an inactivity timeout.

property stdin: Pyjo_IOLoop_Stream | None[source]
stream = child.stdin

Pyjo.IOLoop.Stream object of the standard input of the process, which the reactor writes without an inactivity timeout, and which ends with close_gracefully(). It closes once the process closes its end, so that a write that fails is no error.

property stdout: Pyjo_IOLoop_Stream | None[source]
stream = child.stdout

Pyjo.IOLoop.Stream object of the standard output of the process, which the reactor reads without an inactivity timeout.

# Kill a process that has been quiet for 60 seconds
child.stdout.timeout = 60
child.stdout.on('timeout', lambda stream: child.kill())