Python 3.x 助手线程检查文件系统资源
我正在运行http服务器,它不断地为请求提供服务。 我希望有单独的“助手”线程,检查文件系统中的目录是否可用。 如果资源消失了,那么我希望这个助手线程向主线程返回值,这样我就可以停止http服务器Python 3.x 助手线程检查文件系统资源,python-3.x,python-multithreading,Python 3.x,Python Multithreading,我正在运行http服务器,它不断地为请求提供服务。 我希望有单独的“助手”线程,检查文件系统中的目录是否可用。 如果资源消失了,那么我希望这个助手线程向主线程返回值,这样我就可以停止http服务器 def main(): os.chdir(root) server = HTTPServer(('0.0.0.0', 80), MyHandler) server.serve_forever() 我在想类似的事情 def foo(bar, baz): print 'hel
def main():
os.chdir(root)
server = HTTPServer(('0.0.0.0', 80), MyHandler)
server.serve_forever()
我在想类似的事情
def foo(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz
from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)
async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo
# do some other stuff in the main process
return_val = async_result.get() # get the return value from your function.
如果return_val==“stop”,则停止服务器
这是最好的方法吗?如果你愿意放弃异步的东西(因为老实说,我看不出你需要它的理由) 你可以这么做
while foo():
server.handle_request()
而不是server.serve\u forever()
如果您真的想异步地进行检查,那么您需要显示更多的代码来说明您打算如何使用它,您希望它不断地进行检查吗?偶尔由某些事件触发
编辑:您仍然可以使用while循环,只使用if-inside
while True:
if foo():
server.handle_request()
else:
sleep(1) # or if foo is blocking (like when accessing the file system) you can just not sleep
不管怎样,我最后还是签入了单独的线程, 就这么简单:
import threading
def background_check:
(...)
backgroundCheck = threading.Thread(target=backround_check, args=[directory])
backgroundCheck.start()
谢谢你的快速回复。问题是-服务器正在使用的目录可能会消失一分钟,然后返回。因此,我想关闭服务器1分钟,然后在目录返回时再次启动它。我想类似这样的操作可以实现-2 while循环
而True:while:foo():server.handle\u request()time.sleep(60)os.chdir(dir)