【问题标题】:Python script repeatPython脚本重复
【发布时间】:2022-10-17 08:55:35
【问题描述】:

我在覆盆子上有一个 LED 灯条,想通过颜色在 LED 灯条上指示互联网的状态。

现在我想出了这个:

import os
hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:
    exec(open("random_blink.py").read())

else:
    exec(open("random_blink_colours.py").read())

如何让脚本每 10 秒重新运行一次?

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以将time.sleep() 与循环一起使用:

    import time
    import os
    while True:
        import os
        hostname = "google.com" #example
    
        response = os.system("ping -c 1 " + hostname)
    
        #and then check the response...
    
        if response == 0:
            exec(open("random_blink.py").read())
    
        else:
            exec(open("random_blink_colours.py").read())
    
        time.sleep(10)
    

    我建议也实施停止条件。

    【讨论】:

    • 谢谢!这行得通!
    • @rvdk92 很高兴来到这里!如果这回答了您的问题,我将非常感谢您接受的答案。
    【解决方案2】:

    我确定有更好的方法,但我会尝试

    import os, time
    hostname = "google.com" #example
    
    while True:
        response = os.system("ping -c 1 " + hostname)
    
        #and then check the response...
    
        if response == 0:
            exec(open("random_blink.py").read())
            time.sleep(10)
    
        else:
            exec(open("random_blink_colours.py").read())
    

    【讨论】:

      【解决方案3】:
      import os, time
      
      hostname = "google.com"
      
      while True:
          response = os.system("ping -c 1 " + hostname)
      
          if response == 0:
              exec(open("random_blink.py","r").read())
      
          else:
              exec(open("random_blink_colours.py","r").read())
      
          time.sleep(10)
          
      

      应该做的工作

      【讨论】:

        【解决方案4】:

        只需使用休眠 10 秒的无限循环即可。

        import subprocess
        import time
        
        ...
        
        while True:
            result = subprocess.run(["ping", "-c", "1", hostname])
            to_run = "random_blink.py" if result.returncode == 0 else "random_blink_colors.py"
            subprocess.run([to_run])
            time.sleep(10)
        

        【讨论】:

        • 谢谢我也会试试这个
        猜你喜欢
        • 2019-07-05
        • 1970-01-01
        • 2019-01-05
        • 2019-10-31
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        相关资源
        最近更新 更多