The os.popen function just returns a file-like object. You can use it like so:

import os

process = os.popen('gcc -E myHeader.h')
preprocessed = process.read()
process.close()

As others have said, you should be using subprocess.Popen. It's designed to be a safer version of os.popen. The Python docs have a section describing how to switch over.

Answer from Brian McKenna on Stack Overflow
🌐
Tutorialspoint
tutorialspoint.com › python › os_popen.htm
Python os.popen() Method
import os # Using popen() to execute the 'ls' command fileStream = os.popen("ls") res = fileStream.read() print(res)
Discussions

What should I do if the command 'os. popen' cannot be read again?
echo=os.popen('hostname') echo.read() 'WIN-F2E098\n' echo.seek(0) 0 echo.read() '' .seek(0) of no avail I even tried deep copy, but got an error File "C:\Users\zzz\AppData\Local\Programs\Python\Python310\lib\copy.py", line 161, in deepcopy rv = reductor(4) TypeError: cannot pickle ... More on discuss.python.org
🌐 discuss.python.org
0
0
July 17, 2024
how does the os.popen work()?
os.popen is practically deprecated. Normally you would use subprocess for this. If you just want to read the output until the program finishes then you can use its wrapper check_output docs : h = subprocess.check_output(['type', 'something.py']) More on reddit.com
🌐 r/learnpython
8
4
June 19, 2017
python - os.popen().read() - charmap decoding error - Stack Overflow
I have already read UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to . While the error message is similar, the code is completely More on stackoverflow.com
🌐 stackoverflow.com
September 8, 2018
python - read subprocess stdout line by line - Stack Overflow
However, I found this question ... to set the environment variable PYTHONUNBUFFERED=1 when calling Popen. This works how I want it to, i.e. real-time line-by-line reading of the output of the child process. ... On Linux (and presumably OSX), sometimes the parent process doesn't ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › os.html
os — Miscellaneous operating system interfaces
February 23, 2026 - This function is intended for low-level ... by the built-in function open() or by popen() or fdopen(), or sys.stdin, use its read() or readline() methods....
🌐
Python
docs.python.org › 3 › library › subprocess.html
subprocess — Subprocess management
1 week ago - This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that. ... When the timeout parameter is not None, then (on POSIX) the function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec. Changed in version 3.3: timeout was added. ... Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.
🌐
Educative
educative.io › answers › how-to-perform-command-line-interactions-using-ospopen-in-python
How to perform command line interactions using os.popen in Python
By default, it’s "r" (read) but it can be either "r" (read) or "w" (write). bufsize (optional): This specifies the buffer size. If it is omitted, the default buffering scheme is used. The os.popen() method returns a file object connected to the command’s standard output (if the mode is "r") or standard input (if the mode is "w").
🌐
Python.org
discuss.python.org › python help
What should I do if the command 'os. popen' cannot be read again? - Python Help - Discussions on Python.org
July 17, 2024 - echo=os.popen('hostname') echo.read() 'WIN-F2E098\n' echo.seek(0) 0 echo.read() '' .seek(0) of no avail I even tried deep copy, but got an error File "C:\Users\zzz\AppData\Local\Programs\Python\Python310\lib\copy.py…
🌐
Reddit
reddit.com › r/learnpython › how does the os.popen work()?
r/learnpython on Reddit: how does the os.popen work()?
June 19, 2017 -

The link I found: https://www.tutorialspoint.com/python/os_popen.htm, tells me that os.popen works like a pipe, but my book gives me a very confusing example:
1) open('something.py')

which is because we need an open stream. next it gives:

  h = os.popen('type something.py').read()

At this point, I'm not getting, if os.popen() acts like a pipe('|' on the terminal), then how is this supposed to be pipeing to the stream opened. and what is it piping?

Find elsewhere
🌐
ProgramCreek
programcreek.com › python › example › 142 › os.popen
Python Examples of os.popen
HTTP Header \033[0m" + target) time.sleep(1.5) command = ("http -v " + target) proces = os.popen(command) results = str(proces.read()) print("\033[1;34m" + results + command + "\033[1;m") print ("»"*60 + "\n") except Exception: pass except KeyboardInterrupt: print("\n") print("[-] User Interruption Detected..!") time.sleep(1)
🌐
Stack Abuse
stackabuse.com › pythons-os-and-subprocess-popen-commands
Python's os and subprocess Popen Commands
November 9, 2017 - If you're currently using this ... for Python 3: The code below shows an example of how to use the os.popen method: ... The code above will ask the operating system to list all files in the current directory. The output of our method, which is stored in p, is an open file, which is read and printed ...
🌐
DEV Community
dev.to › waylonwalker › read-stderr-from-python-subprocesspopen-4kc
Read stderr from python subprocess.Popen - DEV Community
February 10, 2022 - import subprocess from subprocess import Popen # this will run the shell command `cat me` and capture stdout and stderr proc = Popen(["cat", "me"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # this will wait for the process to finish. proc.wait() To get the stderr we must get it from the proc, read it, and decode the bystring.
🌐
Python Forum
python-forum.io › thread-13169.html
os.popen output to a list ..
October 2, 2018 - hey all good morning .... im trying to run this command on my system that get my running process in the system import os d = os.popen('''wmic process get name | findstr /v 'Name 'System Idle Process' System''').read().strip() print d #q = ['chro...
🌐
SoByte
sobyte.net › post › 2021-06 › pitfalls-of-os.popen-function-and-pipe-in-python
Pitfalls of os.popen function and Pipe in Python - SoByte
June 29, 2021 - Use the read() function to read the data in the pipe, read it all, and then close it. The standard output of command can also be redirected to /dev/null if the output from the child process is not needed. It can also be run using the subprocess.Popen module of Python3.
🌐
Google Sites
sites.google.com › site › pythonpasapas › modules › os › os-popen
Mon Python pas à pas - os.popen ( )
La méthode os.popen ( ) permet d'exécuter une commande système depuis un script Python et de dévier sa sortie dans un objet fichier, à la place de l'écran de la console, pour consulter le résultat ou interagir avec lui selon la valeur ...
🌐
Medium
medium.com › @asvinjangid.kumar › how-to-store-the-output-of-a-command-in-a-variable-using-python-e7c1b8b91036
Store the Output of a Command in a Variable using Python. | by Ayush Sharma | Medium
January 7, 2024 - Here’s an example: ... In this method, we use `os.popen()` to execute the command `ls -l` and store the output in the `output` variable. The `read()` function is then used to read the output and assign it to the variable.
🌐
Waylon Walker
waylonwalker.com › popen-stderr
Read stderr from python subprocess.Popen - Waylon Walker
February 10, 2022 - import subprocess from subprocess import Popen # this will run the shell command `cat me` and capture stdout and stderr proc = Popen(["cat", "me"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) # this will wait for the process to finish. proc.wait() To get the stderr we must get it from the proc, read it, and decode the bystring.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 40790 › os-popen
python - os.popen [SOLVED] | DaniWeb
March 14, 2006 - # pipe calendar.prmonth(2005, 6) to a string # save the short code within the triple quotes as cal_mar2006.py: """ import calendar calendar.prmonth(2006, 3) """ import os # give full path of .py file so python.exe can find it p = os.popen("python D:/Python24/Atest/cal_mar2006.py") # pipe the output to string str1 str1 = p.read() print str1
🌐
Python Module of the Week
pymotw.com › 2 › subprocess
subprocess – Work with additional processes - Python Module of the Week
Instead, the function is passed to Popen as the preexec_fn argument so it is run after the fork() inside the new process, before it uses exec() to run the shell. import os import signal import subprocess import tempfile import time import sys script = '''#!/bin/sh echo "Shell script in process $$" set -x python signal_child.py ''' script_file = tempfile.NamedTemporaryFile('wt') script_file.write(script) script_file.flush() proc = subprocess.Popen(['sh', script_file.name], close_fds=True, preexec_fn=os.setsid, ) print 'PARENT : Pausing before sending signal to child %s...' % proc.pid sys.stdout.flush() time.sleep(1) print 'PARENT : Signaling process group %s' % proc.pid sys.stdout.flush() os.killpg(proc.pid, signal.SIGUSR1) time.sleep(3)