Python - 从外部命令退出脚本

问题描述

我有一个基于看门狗模块的概念验证脚本,它在将新文件添加到设置文件夹时进行注册并发出命令,该脚本不断运行,但最终设计将放在服务器上,这意味着我们将无法访问命令行以“CTRL + C”它。我如何从外部源(例如激活主脚本中的函数的第二个脚本)杀死它?

这是我当前的脚本,它在底部包含一个“stop_watchdog”函数

from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import os,sys,time
import sqlite3
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

if __name__ == "__main__":
    patterns = ["*"]
    ignore_patterns = None
    ignore_directories = False
    case_sensitive = True
    my_event_handler = PatternMatchingEventHandler(patterns,ignore_patterns,ignore_directories,case_sensitive)

def file_detected(textInput):
    str(textInput)
    if ".txt" not in textInput:
        conn = sqlite3.connect(textInput)  # You can create a new database by changing the name within the quotes
        c = conn.cursor() # The database will be saved in the location where your 'py' file is saved
        c.execute("SELECT * FROM sqlite_master where type = 'table'")
        ##print(c.fetchall())
        textTest = "{}.txt".format(textInput)
        f = open(textTest,"w")
        f.write(str(c.fetchall()))
        f.close()

def on_created(event):
    print(f"hey,{event.src_path} has been created!")
    file_detected(event.src_path)
    ##test("{event.src_path}",shell=True)

my_event_handler.on_created = on_created

path = "./xyz"
go_recursively = True
file_observer = Observer()
file_observer.schedule(my_event_handler,path,recursive=go_recursively)

file_observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    file_observer.stop()
    file_observer.join()

def stop_watchdog():
    print(f"Quitting!")
    file_observer.stop()
    sys.exit()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)