Seems both executes a subprocess and create a pipe to do in/out, just that the subprocess
is newer.
My question is, is there any function that subprocess.Popen
can do while os.popen
cannot, so that we need the new module subprocess
?
Why Python language didn't choose to enhance os.popen
but created a new module?
Short answer: Never use
os.popen
, always usesubprocess
!As you can see from the Python 2.7
os.popen
docs:There were various limitations and problems with the old
os.popen
family of functions. And as the docs mention, the pre 2.6 versions weren't even reliable on Windows.The motivation behind
subprocess
is explained in PEP 324 -- subprocess - New process module:Please see the PEP link for the Rationale, and further details.
Aside from the safety & reliability issues, IMHO, the old
os.popen
family was cumbersome and confusing. It was almost impossible to use correctly without closely referring to the docs while you were coding. In comparison,subprocess
is a godsend, although it's still wise to refer to the docs while using it. ;)Occasionally, one sees people recommending the use of
os.popen
rather thansubprocess.Popen
in Python 2.7, eg Python subprocess vs os.popen overhead because it's faster. Sure, it's faster, but that's because it doesn't do various things that are vital to guarantee that it's working safely!FWIW,
os.popen
itself still exists in Python 3, however it's safely implemented viasubprocess.Popen
, so you might as well just usesubprocess.Popen
directly yourself. The other members of theos.popen
family no longer exist in Python 3. Theos.spawn
family of functions still exist in Python 3, but the docs recommend that the more powerful facilities provided by thesubprocess
module be used instead.