【问题标题】:How can I loop the function in Python, so my script runs all the time?如何在 Python 中循环该函数,以便我的脚本一直运行?
【发布时间】:2021-04-25 08:44:28
【问题描述】:

我想重复运行这个脚本,所以 ping 不会停止并无休止地继续。 我试图用范围和 i

import platform
import win32api
import winsound



def ping_ip(current_ip_address):
        try:
            output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower(
            ) == "windows" else 'c', current_ip_address ), shell=True, universal_newlines=True)
            if 'unreachable' in output:
                return False
            else:
                return True
        except Exception:
                return False


if __name__ == '__main__':
    current_ip_address = ['192.168.8.103', '0.0.0.0']
    for each in current_ip_address:
        if ping_ip(each):
            print(f"{each} is available")
        else:
            winsound.Beep(400, 1000)
            win32api.MessageBox(0, each, 'Device is down')




【问题讨论】:

    标签: python function loops repeat


    【解决方案1】:

    for 循环包裹在一个

    • while True无限运行,等你停止程序
    • for i in range(X) 运行 X 次

    您还可以添加time.sleep 以在每次通话之间暂停一下

    def ping_ip(current_ip_address):
        try:
            mode = 'n' if platform.system().lower() == "windows" else 'c'
            output = subprocess.check_output("ping -{} 1 {}".format(mode, current_ip_address),
                                             shell=True, universal_newlines=True)
            return 'unreachable' not in output
        except Exception:
            return False
    
    
    if __name__ == '__main__':
        current_ip_address = ['192.168.8.103', '0.0.0.0']
        while True:
            for each in current_ip_address:
                if ping_ip(each):
                    print(f"{each} is available")
                else:
                    winsound.Beep(400, 1000)
                    win32api.MessageBox(0, each, 'Device is down')
    
            time.sleep(1)
    

    【讨论】:

      【解决方案2】:

      试试

      while(True):
      

      这将继续运行

      【讨论】:

        【解决方案3】:

        要添加@Shubham Periwal 的答案,您可以使用一个变量来使您的无限循环更加可控:

        switched_on = True
        while switched_on:
            do_things()
            
            if condition:
               switched_on = False
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-09
          • 2020-10-28
          • 2017-04-25
          • 2015-11-14
          • 2018-06-20
          • 1970-01-01
          • 1970-01-01
          • 2023-03-22
          相关资源
          最近更新 更多