Python Glossary Русский

Python 3.8+Linux · macOSosfunction

os.posix_spawn

os — running programs (spawn)

Launch a program via the posix_spawn syscall; returns the PID (3.8+). Availability: Unix.

Syntax

os.posix_spawn(...)

It is faster than fork plus exec for large processes, since the parent's address space need not be copied. subprocess uses it automatically when its parameters allow. Arguments and environment are mandatory: posix_spawn(path, argv, env), where argv starts with the program name and env replaces the environment entirely (since 3.13 it may be None, which inherits the current one). It returns a PID that you must reap with waitpid.

Examples

import os
pid = os.posix_spawn('/bin/echo', ['echo', 'привет'], os.environ)  # → ? только Unix: запускает /bin/echo, печатает «привет» и возвращает PID потомка, например 12345
print(os.waitpid(pid, 0)[1])  # → ? только Unix: 0 — потомок завершился успешно
pid = os.posix_spawn('/bin/sh', ['sh', '-c', 'exit 3'], {'PATH': '/bin:/usr/bin'})  # → ? только Unix: своё окружение вместо os.environ, потомок выйдет с кодом 3
os.posix_spawn('echo', ['echo', 'привет'], os.environ)  # → FileNotFoundError: нужен полный путь, PATH не просматривается (для поиска в PATH — os.posix_spawnp)

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy