Search code examples
pythonpython-3.xsubprocesspywin32

TypeError: 'Popen' object is not callable


I'm trying to query status of a windows service using subprocess module's 'Popen' method. But I'm getting

TypeError: 'Popen' object is not callable

import subprocess, codecs

def serviceStatus(RadiaService):
    status = []
    cmd = 'sc query ' + RadiaService
    pDetails = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
    for item in pDetails():
        status.append(item)
    finalStatus = b''.join(status).decode('utf-8')
    print(finalStatus)

if __name__ == '__main__':
    serviceStatus('RCA')

Error Trace :

Traceback (most recent call last):
  File "C:\Alen\Cumulative RHF\Radia_Cumulative_Patch\cumulativeHotFixproject\lib\win32.py", line 39, in <module>
    serviceStatus('RCA')
  File "C:\Alen\Cumulative RHF\Radia_Cumulative_Patch\cumulativeHotFixproject\lib\win32.py", line 33, in serviceStatus
    for item in pDetails():
TypeError: 'Popen' object is not callable

Solution

  • It looks like you wish to collect the standard output of the subprocess. You will have to use pDetails.stdout. Here is an example to help you get started:

    import subprocess
    p = subprocess.Popen("ls -la", shell=True, stdout=subprocess.PIPE)
    output = b''.join(p.stdout).decode('utf-8')
    print(output)
    

    Based on that this is how your code should look like:

    import subprocess, codecs
    
    def serviceStatus(RadiaService):
        cmd = 'sc query ' + RadiaService
        pDetails = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
        return b''.join(pDetails.stdout).decode('utf-8')
    
    def main():
        print(serviceStatus('RCA'))
    
    if __name__ == '__main__':
        main()
    

    Note: you don't have to collect the output in a list, you can feed the iterable directly to join. If you need a list, you still don't have to use a for loop, you can just write status = list(pDetails.stdout).