Name

popen

Synopsis

popen(cmd,mode='r',bufsize=-1)

Runs the string command cmd in a new process P, and returns a file-like object f that wraps a pipe to P’s standard input or from P’s standard output (depending on mode). mode and bufsize have the same meaning as for Python’s built-in open function, covered in Chapter 10. When mode is 'r' (or 'rb', for binary-mode reading), f is read-only and wraps P’s standard output. When mode is 'w' (or 'wb', for binary-mode writing), f is write-only and wraps P’s standard input.

The key difference of f with respect to other file objects is the behavior of method f .close. f .close waits for P to terminate, and returns None, as close methods of file-like objects normally do, when P’s termination is successful. However, if the operating system associates an integer error code with P’s termination indicating that P’s termination was unsuccessful, f .close also returns c. Not all operating systems support this mechanism: on some platforms, f .close therefore always returns None. On Unix-like platforms, if P terminates with the system call exit( n ) (e.g., if P is a Python program and terminates by calling sys.exit( n )), f .close receives from the operating system, and returns to f .close’s caller, the code 256* n.

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.