【发布时间】:2021-07-24 12:29:12
【问题描述】:
我正在尝试编写一个 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)
【问题讨论】:
-
我不明白为什么要为此任务编写 Python 脚本。可以在command prompt 窗口中分别执行
sc query和完整的限定文件名%SystemRoot%\System32\sc.exe query。此外,我不明白使用 Python 脚本有什么好处,该脚本使用了一个额外的脚本解释器(如 PowerShell)来执行主要任务,该任务使用 Windows 默认安装的最旧的脚本解释器运行,这是不必要的 - Windows 命令处理器cmd.exe。为什么要为一项任务使用三个脚本解释器? -
如果您想使用 Python 脚本捕获和显示
C:\Windows\System32\cmd.exe /c powershell -command "get-service *searchbar* |ft -HideTableHeaders"的标准输出stdout和searchbar,我建议您仔细完整地阅读 subprocess module 的 Python 文档我们的未知字符串值和cmd.exe搜索名称为powershell的文件,希望找到%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe。 -
我建议还仔细并完整地阅读有关 Windows 内核库函数 CreateProcess 的 Microsoft 文档,
subprocess.run()、subprocess.call()` 和subprocess.Popen()在 Windows 上使用它来运行在shell=True上,Windows 命令处理器cmd.exe由环境变量ComSpec定义,选项/c和作为参数附加的命令行,发现powershell.exe也使用CreateProcess来运行PowerShell 可执行文件。跨度> -
在这种情况下,使用
cmd.exe和powershell.exe获取与通配符模式与变量searchbar的字符串值匹配的服务列表,这对您打开命令非常有用提示窗口,运行cmd /?并仔细阅读输出帮助解释了不必要的使用Windows 命令处理器如何解释选项/c之后的参数,这不容易理解,但在Python 代码中必须考虑。三种不同语法规则的三个脚本解释器的使用,真的不好处理。
标签: python-3.x windows powershell cmd scripting