Search code examples
pythonpython-3.xsubprocesspopen

How to use subprocess.Popen() instead of os.popen() in Python?


Since os.popen is deprecated, I wanted to use subprocess.Popen (and also because it is a lot more robust in every sense). I had this initially but can't figure out how to make the appropriate transition.

PID_FILE = 'process.pid'
if os.path.exists( PID_FILE ):
    pid = int(open( PID_FILE,'rb').read().rstrip('\n'))
    pinfo = os.popen('ps %i' % pid).read().split('\n')

Any help would be appreciated a lot.


Solution

  • Just use subprocess.Popen to create a new process, with its stdout redirected to a PIPE, in text mode and then read its stdout.

    Python version >= 3.6

    from subprocess import Popen, PIPE
    with Popen(f'ps {pid}'.split(), stdout=PIPE, text=True) as proc:
        pinfo = proc.stdout.readlines()
    

    As you have requested for python2.7, I have given the code. But remember that python2.7 has reached EOL and you should be using python3.x

    Python version = 2.7

    from subprocess import Popen, PIPE
    proc = Popen(f'ps {pid}'.split(), stdout=PIPE)
    pinfo = proc.stdout.readlines()
    

    Refer subprocess documentation for more information