Python os.dup2() Method
os.dup2 Overview
The os.dup2() method is used to copy one file descriptor fd to another fd2.
Available on Unix, Windows.
os.dup2 Syntax
The dup2() method syntax format is as follows:
os.dup2(fd, fd2);
os.dup2 Parameters
- fd – the file descriptor to be copied
- fd2 – copied file descriptors
os.dup2 Return Value
No return value.
os.dup2 Demo
The following example demonstrates the use of the dup2() method.
import os
# Open a file
f = open('apidemos.txt', 'a')
# Pass the file represented by this file descriptor to the file pointed to by the 1 descriptor (i.e. stdout)
os.dup2(f.fileno(), 1)
# Close file
f.close()
# print Output to the standard output stream, which is the file descriptor 1
print('apidemos.com')
print('google')
The output of the above program is, generates a txt file with the following content: