all Python 3osfunction
os.dup2
os — file descriptors
Duplicate fd onto fd2 (closing fd2 first if needed) and return fd2.
Syntax
os.dup2(fd, fd2)
If fd2 was open it is closed silently — this is how standard streams are redirected at the OS level: dup2(fileno, 1) sends the output of child programs and C libraries to the file as well. Merely replacing sys.stdout does not achieve that. The new descriptor is inheritable by default (inheritable=True).
Examples
import os
fd = os.open(os.__file__, os.O_RDONLY)
fd2 = os.dup(fd)
print(os.dup2(fd, fd2) == fd2) # → True
os.close(fd)
os.close(fd2)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy