Python os.dup() Method



The Python os.dup() method returns a duplicate of the given file descriptor. It means that the duplicate can be used in place of the original descriptor.

The new file descriptor obtained is non-inheritable. By non-inheritable, we mean that the created file descriptor cannot be inherited by the child processes. All the non-inheritable file descriptors in child processes are closed.

But on the Windows platform, file descriptors associated with standard stream such as standard input: 0, standard output: 1, and standard error: 2 can be inherited by the child processes.

If the parent process is using file descriptor 3 for a specific file and the parent creates a child process, the child process will also be using file descriptor 3 for the same file. This is known as an inheritable file descriptor.

Syntax

Following is the syntax of Python os.dup() method −

os.dup(fd)

Parameters

  • fd − This is the original file descriptor.

Return Value

This method returns a duplicate of file descriptor.

Example

The following example shows the usage of Python os.dup() method. Here a file is opened for reading and writing. Then a duplicate file is obtained by the method−

import os, sys
# Open a file
fd = os.open( "code.txt", os.O_RDWR|os.O_CREAT )
# Get one duplicate file descriptor
d_fd = os.dup( fd )
# Write one string using duplicate fd
string = "This is test"
x = str.encode(string)
os.write(d_fd, x)
# Close a single opened file
os.closerange( fd, d_fd)
print ("Closed all the files successfully!!")

When we run above program, it produces following result −

Closed all the files successfully!!

Example

In the following example the file is open in read only by owner mode. The duplicate file will have different value but it will correspond to the same file to which original file descriptor was referring.

import os
import stat
# File path
path = "code.txt"
# opening the file for reading only by owner
filedesc = os.open(path, stat.S_IREAD)
print("The original file descriptor is:", filedesc)
# Duplicating the file descriptor
dup_filedesc = os.dup(filedesc)
print("The duplicated file descriptor is:", dup_filedesc)

While executing the above code we get the following output −

The original file descriptor is: 3
The duplicated file descriptor is: 4
os_file_methods.htm
Advertisements