简体   繁体   English

Python 如果功能未按预期工作

[英]Python if funtion not working as intended

I took Python last year in college and likeed it so much I decided to start using it or at least try.去年我在大学里学习了 Python 并且非常喜欢它,我决定开始使用它或者至少尝试一下。

I'm struck on the below code.我对下面的代码感到震惊。 Basically I want it to only print the service that was stopped or started, but it's printing the services all the time.基本上我希望它只打印停止或启动的服务,但它一直在打印服务。 Below is part of the code I have.以下是我拥有的代码的一部分。 I'm still very new to Python, so I know this must be something I'm doing wrong.我对 Python 还是很陌生,所以我知道这一定是我做错了。

c = wmi.WMI()

  for s in c.Win32_Service():
    if s.State == 'Stopped':
            service_name = ['SolarWindsAdministration','SolarWindsAgent64','SolarWindsAlertingServiceV2'
                      ,'SWCollectorService','SolarWindsCortex','SWInfoServiceSvc','SWInfoServiceSvcV3','SWJobEngineSvc2',
                      'SWBrowserIntegration','SolarWindsRecommendations','SolarWindsSyslogService',
                      'SolarWinds TFTP Server',
                      'SolarWinds NetPerfMon',][enter image description here][1]
            s.StartService(service_name)
            print(service_name, s.State)

In the copy/pasted code, when defining service_name, [enter image description here][1] does not make sense.在复制/粘贴代码中,定义service_name时, [enter image description here][1]没有意义。 I assume it is a typo.我认为这是一个错字。 From what you said, here is an example of corrected code (for restarting services).根据您的说法,这是一个更正代码示例(用于重新启动服务)。 You still have to adapt it if you want to stop services.如果您想停止服务,您仍然必须对其进行调整。

import wmi
services_to_monitor = ['SolarWindsAdministration','SolarWindsAgent64',
                       'SolarWindsAlertingServiceV2','SWCollectorService',
                       'SolarWindsCortex','SWInfoServiceSvc',
                       'SWInfoServiceSvcV3','SWJobEngineSvc2',
                       'SWBrowserIntegration','SolarWindsRecommendations',
                       'SolarWindsSyslogService','SolarWinds TFTP Server',
                       'SolarWinds NetPerfMon']
c = wmi.WMI()
for service in c.Win32_Service():
    if service.Name in services_to_monitor and service.State == 'Stopped':
        result, = service.StartService()        
        if result == 0:
            print("Service " +str(service.Name)+" started")
        else:
            print("Oops. Something went wrong starting "+str(service.Name))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM