python中是否有一个Observer和一个Event Handler来响应文件修改



我有HTML代码,可以与服务器对话(只是一个php脚本(,并将用户输入写入json文件。然而,现在我想编写python,当json文件被修改时,它会注意到并读取新值。我环顾四周,发现了对看门狗和许多示例的引用,但每次修改文件时,所有示例似乎都会抛出相同的错误。以下是其中一个例子(其他例子没有明显区别(:

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class EventHandler(FileSystemEventHandler):
def on_any_event(self, event):
print event

if __name__ == "__main__":
path = "/PATH/TO/YOUR/FOLDER"
event_handler = EventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()

该错误给出了json文件的路径,然后是Bad file descriptor(它为文件路径中的每个目录都做了一次(。我对此进行了研究,这是由我从代码外部修改Json文件引起的(出于测试目的,我在文本编辑器中进行了修改(,这就是PHP脚本无论如何都会发生的事情。在我看来,解决这个问题有两种方法。要么以某种方式连接python和php,使python成为服务器的一部分,要么在文件系统中找到一种新的事件监视方法。我该怎么办?

我得到了。可以将php连接到python。本质上,两者都可以使用标准化的输出流,因此当您在python中打印时,它会被放入php中,因此连接可以双向工作。在php中,设置变量,然后使用shell_exec命令:

$variableToPassToPython="hi";
$result=shell_exec('Path to python that you use Path to py file that you want to run ' . $variableToPassToPython);
//that will concatenate the variable to the terminal command(shell_exc runs terminal commands) to be sent to the python as an arg

现在,要访问在命令行中传递给python的变量,请在python中执行以下操作:

import sys
hi=sys.argv[1]#argv[0] is the path of the python file, and argv returns a list of all arguments passed through command line
print(hi+' world!')
#remember that in this case, printing means sending something back to the php file

这可以让你在php中做一些很酷的事情(下面的代码假设你已经在上面的代码中运行了python(:

echo $result
//result was the variable that was assigned to the shell_exec command, and that command returns whatever python prints to it

上面的代码看起来像这样:

hi world!
你可以看到这打开了比更多的大门

重要事项:我最初做这件事时遇到了问题。如果您在php中使用POST请求的输入,那么这是一个数组,shell_exec转换为字符串。在php中,当您将数组强制转换为字符串时,它就变成了单词";数组";。要解决此问题,请使用内爆((函数,该函数可以将数组正确地转换为字符串,以便将其作为shell命令传递

最新更新