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.
SyntaxFollowing 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).
The Python os.popen() method returns an open file object connected to the pipe.
ExampleThe 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4