如何在按下 ‘q’ 键后终止脚本?

huangapple go评论150阅读模式
英文:

How do I terminate the script once 'q' is pressed?

问题

下面是一个完整的脚本,我正在尝试自动化多个路由器的ping过程,并每2小时执行一次,但我还希望能够随时终止它。

  1. def start():
  2. for file_name in file_list:
  3. unrechable = []
  4. rechable = []
  5. print("处理中:" + file_name, end="\n")
  6. open_file(file_name, rechable, unrechable)
  7. if len(unrechable) > 0:
  8. print(file_name + "中的不可达IP:")
  9. for i in unrechable:
  10. print(i, end="\n")
  11. print("")
  12. else:
  13. print(file_name + "中的所有IP均可达")
  14. return
  15. def open_file(file_name, rechable, unrechable):
  16. df = pd.read_excel("D:/Network/" + file_name + ".xlsx")
  17. col_IP = df.loc[:, "IP"].tolist()
  18. col_name = df.loc[:, "Location"].tolist()
  19. check(col_IP, col_name, rechable, unrechable)
  20. return
  21. def check(col_IP, col_name, rechable, unrechable):
  22. for ip in range(len(col_IP)):
  23. response = os.popen(f"ping {col_IP[ip]} ").read()
  24. if "Request timed out." in response or "unreachable" in response:
  25. print(response)
  26. unrechable.append(str(col_IP[ip] + "位于" + col_name[ip]))
  27. else:
  28. print(response)
  29. rechable.append(str(col_IP[ip] + "位于" + col_name[ip]))
  30. return
  31. def main1():
  32. while True:
  33. start()
  34. print("休眠2小时")
  35. time.sleep(7200)
  36. def qu():
  37. while True:
  38. if keyboard.is_pressed('q'):
  39. print("退出")
  40. os._exit(0)
  41. file_list = ["ISP", "NVR"]
  42. if __name__ == '__main__':
  43. p2 = Thread(target=main1)
  44. p3 = Thread(target=qu)
  45. p2.start()
  46. p3.start()

我在这里创建了两个线程,一个运行主要脚本,另一个监听键盘中断。但一旦按下 'q' 键,只有一个线程终止。后来我发现不可能同时终止两个线程,我在这一点上完全迷失了方向。

英文:

Below is a complete script I am trying to automate the process of pinging multiple routers and to do that every 2 hrs but I also want the ability to terminate it at any given time.

  1. def start():
  2. for file_name in file_list:
  3. unrechable = []
  4. rechable = []
  5. print("Processing:"+file_name,end="\n")
  6. open_file(file_name, rechable, unrechable)
  7. if len(unrechable) > 0:
  8. print("These IP from " + file_name + " are Unrechable:")
  9. for i in unrechable:
  10. print(i,end="\n")
  11. print("")
  12. else:
  13. print("All IP's are Rechable from " + file_name)
  14. return
  15. '''
  16. '''
  17. def open_file(file_name, rechable, unrechable):
  18. df = pd.read_excel("D:/Network/"+file_name+".xlsx")
  19. col_IP = df.loc[:, "IP"].tolist()
  20. col_name = df.loc[:, "Location"].tolist()
  21. check(col_IP, col_name, rechable, unrechable)
  22. return
  23. '''
  24. '''
  25. def check(col_IP, col_name, rechable, unrechable):
  26. for ip in range(len(col_IP)):
  27. response = os.popen(f"ping {col_IP[ip]} ").read()
  28. if("Request timed out." or "unreachable") in response:
  29. print(response)
  30. unrechable.append(str(col_IP[ip] + " at " + col_name[ip]))
  31. else:
  32. print(response)
  33. rechable.append(str(col_IP[ip] + " at " + col_name[ip]))
  34. return
  35. '''
  36. '''
  37. def main1():
  38. while(True):
  39. start()
  40. print("Goint to Sleep for 2Hrs")
  41. time.sleep(60)
  42. def qu():
  43. while(True):
  44. if(keyboard.is_pressed('q')):
  45. print("exit")
  46. os._exit
  47. '''
  48. '''
  49. file_list = ["ISP" , "NVR"]
  50. if __name__ == '__main__':
  51. p2 = Thread(target=main1)
  52. p3 = Thread(target=qu)
  53. p2.start()
  54. p3.start()

I have created 2 threads here one runs the main script the other looks for keyboard interrupt. But once q is pressed only one of the threads terminates. I later found out it is impossible to terminate both threads at one and I am completely lost at this point

答案1

得分: 3

我认为你应该在主线程中监听键盘中断。然后,你可以在中断时调用 p2.join()

但是为什么要使用 qCtrl+C 对你不起作用吗?那是默认的中断方式。这样你就不需要实现其他特殊逻辑。

英文:

I think you should listen for the keyboard interrupts in the main thread. Then you can call p2.join() upon interrupt.

But why do it with q? Doesn't Ctrl+C work for you? That is the default interrupt. Then you don't have to implement any other special logic.

答案2

得分: 2

你可以使用 timedInput()

首先运行这些命令:

  1. python3 install pip
  2. pip install --upgrade pip
  3. pip3 install pytimedinput

确保导入它:

  1. from pytimedinput import timedInput

退出脚本:

  1. var_name, timesup = timedInput("", 60, False, 0)
  2. if var_name[0] == "q":
  3. quit()
英文:

You can use timedInput()

First run these commands:

python3 install pip

pip install --upgrade pip

pip3 install pytimedinput

Make sure you import it:

  1. from pytimedinput import timedInput

Quit script:

  1. var_name,timesup = timedInput("",60,False,0)
  2. if ((var_name)[0])=="q":
  3. quit()

答案3

得分: 0

  1. 我在一个监听键盘中断的线程中添加了一个队列一旦满足条件就将其加入队列
  2. ```python
  3. def qu1():
  4. while(True):
  5. if keyboard.is_pressed("q"):
  6. qu_main.put("q")
  7. print("添加了q")
  8. break
  9. else:
  10. pass
  11. return

接下来我将睡眠定时器放入了一个循环中。
我希望我的脚本以2小时间隔执行,因此我添加了一个1秒的定时器,并将其循环了7200次。

  1. while(x < 7200):
  2. if(not qu_main.empty()):
  3. if(qu_main.get() == 'q'):
  4. print("结束循环")
  5. return
  6. else:
  7. print("睡眠")
  8. x += 1
  9. time.sleep(1)
  10. else:
  11. print("睡眠")
  12. x += 1
  13. time.sleep(1)
英文:

I added a queue to a thread that listens to any keyboard interrupts and once the condition is met adds it to the queue.

  1. def qu1():
  2. while(True):
  3. if keyboard.is_pressed(&quot;q&quot;):
  4. qu_main.put(&quot;q&quot;)
  5. print(&quot;added q&quot;)
  6. break
  7. else:
  8. pass
  9. return

Next I put my sleep timer in a loop.
I wanted my script to execute in 2hr intervals therefore I added a 1s timer and looped it 7200 times.

  1. while(x &lt; 7200):
  2. if(not qu_main.empty()):
  3. if(qu_main.get() == &#39;q&#39;):
  4. print(&quot;ending the Cycle&quot;)
  5. return
  6. else:
  7. print(&quot;sleep&quot;)
  8. x += 1
  9. time.sleep(1)
  10. else:
  11. print(&quot;sleep&quot;)
  12. x += 1
  13. time.sleep(1)

huangapple
  • 本文由 发表于 2023年7月13日 19:02:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定