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

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

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

问题

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

def start():
    for file_name in file_list:
        unrechable = []
        rechable = []
        print("处理中:" + file_name, end="\n")
        open_file(file_name, rechable, unrechable)

        if len(unrechable) > 0:
            print(file_name + "中的不可达IP:")
            for i in unrechable:
                print(i, end="\n")
            print("")
        else:
            print(file_name + "中的所有IP均可达")
    return

def open_file(file_name, rechable, unrechable):
    df = pd.read_excel("D:/Network/" + file_name + ".xlsx")
    col_IP = df.loc[:, "IP"].tolist()
    col_name = df.loc[:, "Location"].tolist()
    check(col_IP, col_name, rechable, unrechable)
    return

def check(col_IP, col_name, rechable, unrechable):
    for ip in range(len(col_IP)):
        response = os.popen(f"ping {col_IP[ip]} ").read()
        if "Request timed out." in response or "unreachable" in response:
            print(response)
            unrechable.append(str(col_IP[ip] + "位于" + col_name[ip]))
        else:
            print(response)
            rechable.append(str(col_IP[ip] + "位于" + col_name[ip]))
    return

def main1():
  while True:
      start()
      print("休眠2小时")
      time.sleep(7200)

def qu():
  while True:
      if keyboard.is_pressed('q'):
          print("退出")
          os._exit(0)

file_list = ["ISP", "NVR"]

if __name__ == '__main__':
    p2 = Thread(target=main1)
    p3 = Thread(target=qu)

    p2.start()
    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.

def start():
    for file_name in file_list:
        unrechable = []
        rechable = []
        print("Processing:"+file_name,end="\n")
        open_file(file_name, rechable, unrechable)

        if len(unrechable) > 0:
            print("These IP from " + file_name + " are Unrechable:")
            for i in unrechable:
                print(i,end="\n")
            print("")
        else:
            print("All IP's are Rechable from " + file_name)
    return
'''
'''

def open_file(file_name, rechable, unrechable):
    df = pd.read_excel("D:/Network/"+file_name+".xlsx")
    col_IP = df.loc[:, "IP"].tolist()
    col_name = df.loc[:, "Location"].tolist()
    check(col_IP, col_name, rechable, unrechable)
    return
'''
'''

def check(col_IP, col_name, rechable, unrechable):
    for ip in range(len(col_IP)):
        response = os.popen(f"ping {col_IP[ip]} ").read()
        if("Request timed out." or "unreachable") in response:
            print(response)
            unrechable.append(str(col_IP[ip] + " at " + col_name[ip]))
        else:
            print(response)
            rechable.append(str(col_IP[ip] + " at " + col_name[ip]))
    return
'''
'''
def main1():
  while(True):
      start()
      print("Goint to Sleep for 2Hrs")
      time.sleep(60)

def qu():
  while(True):
      if(keyboard.is_pressed('q')):
          print("exit")
          os._exit
'''
'''  

file_list = ["ISP" , "NVR"]

if __name__ == '__main__':
    

    p2 = Thread(target=main1)
    p3 = Thread(target=qu)

    p2.start()
    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()

首先运行这些命令:

python3 install pip

pip install --upgrade pip

pip3 install pytimedinput

确保导入它:

from pytimedinput import timedInput

退出脚本:

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

You can use timedInput()

First run these commands:

python3 install pip

pip install --upgrade pip

pip3 install pytimedinput

Make sure you import it:

from pytimedinput import timedInput

Quit script:

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

答案3

得分: 0

我在一个监听键盘中断的线程中添加了一个队列一旦满足条件就将其加入队列

```python
def qu1():
    while(True):
        if keyboard.is_pressed("q"):
            qu_main.put("q")
            print("添加了q")
            break
        else:
            pass
    return

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

while(x < 7200):
    if(not qu_main.empty()):
        if(qu_main.get() == 'q'):
            print("结束循环")
            return
        else:
            print("睡眠")
            x += 1
            time.sleep(1)
    else:
        print("睡眠")
        x += 1
        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.

def qu1():
    while(True):
        if keyboard.is_pressed(&quot;q&quot;):
            qu_main.put(&quot;q&quot;)
            print(&quot;added q&quot;)
            break
        else:
            pass
    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.

while(x &lt; 7200):
            if(not qu_main.empty()):
                if(qu_main.get() == &#39;q&#39;):
                    print(&quot;ending the Cycle&quot;)
                    return
                else:
                    print(&quot;sleep&quot;)
                    x += 1
                    time.sleep(1)
            else:
                print(&quot;sleep&quot;)
                x += 1
                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:

确定