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.ChildProcessinherits all methods fromPyjo.EventEmitterand implements the following new ones.- property exit_code: int | None[source]¶
code = child.exit_code
Exit code of the process, or
Noneif 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,
SIGTERMby default, if it is still running, or to the processes of its group, which it may have started, when it has been spawneddetached, while any of them runs.
- property reactor: Pyjo_Reactor[source]¶
reactor = child.reactor child.reactor = Pyjo.Reactor.Poll.new()
Low-level event reactor, defaults to the
reactorattribute value of the globalPyjo.IOLoopsingleton. 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 ofspawn(), but writesinputto the standard input of the process and ends it, and returns aPyjo.Promiseobject, which is fulfilled with the exit code,Nonefor a signal, and the whole output and error of the process asPyjo.String.Bytesobjects 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 directorycwdand with the environmentenv, the ones of this process by default. Withdetached, the process runs in a session of its own, as the leader of a process group, asdetachedof Node.js, so thatkill()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 eventsspawnorerrorare 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 eventspawnon.
- property stderr: Pyjo_IOLoop_Stream | None[source]¶
stream = child.stderr
Pyjo.IOLoop.Streamobject 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.Streamobject of the standard input of the process, which the reactor writes without an inactivity timeout, and which ends withclose_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.Streamobject 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())