Python os.popen() Method



The Python os.popen() method provides a way to run shell commands using Python code. It works by opening a pipe to or from command line. The return value of this method is an open file object which is connected to the pipe. This helps in reading and writing operations depending on the specified mode.

Syntax

Following is the syntax for Python os.popen() method −

os.popen(command, mode, bufsize)

Parameters

The Python os.popen() method accepts the following parameters −

  • command − It specifies a command that needs to be executed.

  • mode − This parameter specifies the mode in which the file object is opened. Its default value is "r" which indicates reading.

  • bufsize − If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action will be performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

Return Value

The Python os.popen() method returns an open file object connected to the pipe.

Example

The following example shows the usage of popen() method where we are executing the "mkdir" command.

import os, sys

# using command mkdir
a = "mkdir nwdir"

b = os.popen(a,"r",1)
print (b)

When we run above program, it will create a directory named "nwdir" with read mode.

<os._wrap_close object at 0x74f4dbd26e60>

Example

In this example, we are executing the "ls" command which lists the files available inside the current working directory.

import os

# Using popen() to execute the 'ls' command
fileStream = os.popen("ls")
res = fileStream.read()
print(res)

When we run above program, it produces following result −

aa.txt
atty.py
chown.py
cwd.py
datasync.py
dsync.py
exp.txt
fdopen.py
foo.txt
fopen.py
python_files_io.htm
Advertisements