gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:43:49 32 4
gpt4 key购买 nike

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

TypeError: '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()

注意:您不必将输出收集到列表中,您可以直接将 iterable 提供给 join。如果你需要一个列表,你仍然不必使用for循环,你可以只写status = list(pDetails.stdout)

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

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com