Python 3.x 正在尝试创建服务搜索器

Python 3.x 正在尝试创建服务搜索器,python-3.x,windows,powershell,cmd,scripting,Python 3.x,Windows,Powershell,Cmd,Scripting,我正在尝试使用python脚本搜索windows服务,并在一个列表框中显示它们的名称、显示名称和状态,但到目前为止,我所做的只是显示一个零。在下面的对话框中,我可以看到3个输出,但我不知道如何将它们放入下面的列表框中 def search_query(searchbar): NameSave=("powershell -command "+'"'+"get-service *"+ searchbar+'* |ft -HideTableHe

我正在尝试使用python脚本搜索windows服务,并在一个列表框中显示它们的名称、显示名称和状态,但到目前为止,我所做的只是显示一个零。在下面的对话框中,我可以看到3个输出,但我不知道如何将它们放入下面的列表框中

def search_query(searchbar):
    NameSave=("powershell -command "+'"'+"get-service *"+ searchbar+'* |ft -HideTableHeaders"')
    NameList=subprocess.call(NameSave, shell=True)
    serviceslist.insert(0,NameList)


searchf= tk.Frame(root, 
    bg="#20179a")
searchf.place(relx=0.5, 
    rely= 0.3, 
    relwidth=0.6, 
    relheight=0.075, 
    anchor="n")
searchbar= tk.Entry(searchf,
    font="Helvetica 18 bold",
    justify="center")
searchbar.place(relx=0.4,
    rely=0.5,
    relwidth=0.65, 
    relheight=0.8, 
    anchor="center")
searchbutton=tk.Button(searchf,
    text="Search Service",
    font="Helvetica 16 bold",
    fg="#20179a",
    bd=0,
    command= lambda: search_query(searchbar.get()))
searchbutton.place(relx=0.75,
    rely=0.5,
    relwidth=0.2,
    relheight=0.8, 
    anchor="w")



servicesf=tk.Frame(root,
    bg="#20179a")
servicesf.place(relx=0.05,
    rely=0.4,
    relwidth=0.9,
    relheight=0.45)
serviceslist=tk.Listbox(servicesf, font="Helvetica 18 bold")
serviceslist.place(relx=0.025,
    rely=0.1,
    relwidth=0.95,
    relheight=0.8)


对于这个问题,有一个PowerShell本机解决方案,只需几行代码

Get-Service |Out-GridView -passthru `
   -Title "All Services on $($env:COMPUTERNAME), Select one or more for additional info" |
    Format-List 
生成此用户界面

然后,结果可以存储在一个变量中供以后使用,或者发送到另一个命令,如本例中的
格式列表


我不明白为什么要为此任务编写Python脚本。可以在窗口
sc query
中分别使用完全限定的文件名
%SystemRoot%\System32\sc.exe query
执行查询。此外,我不明白使用Python脚本的好处是什么,该脚本使用一个以上的脚本解释器(如PowerShell)来执行主任务,而不需要使用默认安装在Windows上的最旧脚本解释器运行—Windows命令处理器
cmd.exe
。为什么一项任务要使用三个脚本解释器?请参阅或中的其他问题和答案。如果要捕获并显示
C:\Windows\System32\cmd.exe/C powershell-command的标准输出
stdout
,建议仔细完整地阅读的Python文档“获取服务*搜索栏*| ft-HideTableHeaders”"
使用
searchbar
作为我们未知的字符串值,使用
cmd.exe
搜索名为
powershell
的文件,希望找到
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
。我建议您也仔细完整地阅读针对Windows的Microsoft文档在Windows上由
subprocess.run()
、subprocess.call()和
subprocess.Popen()使用的内核库函数
在Windows命令处理器
cmd.exe
上运行,该处理器由环境变量
ComSpec
定义,带有选项
/c
,命令行作为参数附加,在找到
powershell.exe
后也使用
CreateProcess
运行powershell可执行文件。在这种情况下通过使用
cmd.exe
powershell.exe
获取与通配符模式和变量
searchbar
字符串值相匹配的服务列表,打开命令提示窗口将非常有用,运行
cmd/?
并仔细阅读输出帮助,解释不必要的Windows命令处理器如何解释选项
/c
后的参数,这不容易理解,但在Python代码中必须加以考虑。使用具有三种不同语法规则的三个脚本解释器确实不容易处理。