如何在 Python 中循环函数,以便我的脚本一直运行?

How can I loop the function in Python, so my script runs all the time?

我想 运行 重复执行此脚本,这样 ping 就不会停止并无休止地继续。 我尝试使用范围循环函数,而 i<9999 但我出现错误“TypeError: ping_ip() missing 1 required positional argument: 'current_ip_address'。如果我 copy/paste 函数全部然后在脚本中重新 运行 毫无问题地转到下一个脚本。请问有什么想法吗?:

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')




尝试

while(True):

这将继续运行

内包装 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)

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

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