python - 类型错误 : 'Popen' object is not callable

标签 python python-3.x subprocess pywin32

我正在尝试使用子进程模块的“Popen”方法查询 Windows 服务的状态。但我越来越

类型错误:“Popen”对象不可调用

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')

错误跟踪:

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

最佳答案

您似乎希望收集子流程的标准输出。您必须使用pDetails.stdout。以下是帮助您入门的示例:

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

基于此,您的代码应该如下所示:

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()

注意:您不必将输出收集到列表中,您可以直接将可迭代对象提供给连接。如果需要列表,仍然不必使用 for 循环,只需编写 status = list(pDetails.stdout) 即可。

关于python - 类型错误 : 'Popen' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719307/

相关文章:

python - 多处理python不并行运行

用于在某些两个字符串之间提取字符串的 python 正则表达式

包装需要大量参数的子进程调用的 Pythonic 方法?

python - 如何获取Popen中的shell变量值

python - 如何以 pythonic 方式填充 Pandas dataframe 缺失的记录?

python - 如何在 Python 中读取键盘输入

python - pandas 列值和变量值字符串连接

Python:绘制非重叠圆圈 - 递归失败, 'while' 有效

python - SSL 证书验证失败 (_ssl.c :600)

python - 在 python 中发出连续命令?