office_helper.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import functools
  2. import json
  3. import os.path
  4. import sys
  5. import threading
  6. if getattr(sys, 'frozen', False):
  7. # 打包后的 exe
  8. os.chdir(os.path.dirname(sys.executable))
  9. else:
  10. # 普通 Python 脚本
  11. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  12. from config import dl_code
  13. from core.api_app import start_flask
  14. from core.monitor_file import start_watchdog
  15. from tools.logger_handle import logger
  16. from tools.serve_client import ServerClient
  17. def ApplicationInstance(func):
  18. @functools.wraps(func)
  19. def fun(*args, **kwargs):
  20. import socket
  21. try:
  22. global s
  23. s = socket.socket()
  24. host = socket.gethostname()
  25. s.bind((host, 60123))
  26. except:
  27. logger.error('不能重复打开已存在的程序')
  28. return None
  29. return func(*args, **kwargs)
  30. return fun
  31. # 启动所有后台服务
  32. @ApplicationInstance
  33. def start_all_services(serve_client, work_path):
  34. # 启动 Flask 服务
  35. threading.Thread(target=start_flask, args=[serve_client, work_path], daemon=True).start()
  36. # 启动文件监控
  37. threading.Thread(target=start_watchdog, args=[serve_client, work_path], daemon=True).start()
  38. logger.info('server running')
  39. while True:
  40. a = 0
  41. if __name__ == "__main__":
  42. if not os.path.exists(f'{dl_code}:\\ProgramData\\OfficeAssistant\\config.json'):
  43. logger.error('"config.json" is not find')
  44. sys.exit(0)
  45. with open(f'{dl_code}:\\ProgramData\\OfficeAssistant\\config.json', 'r', encoding='utf-8') as f:
  46. # with open(f'config.json', 'r', encoding='utf-8') as f:
  47. args = json.load(f)
  48. if not (args.get('server') and args.get('username') and args.get('password')):
  49. logger.error('The config is missing critical information')
  50. sys.exit(0)
  51. client = ServerClient(args['server'], args['username'], args['password'])
  52. if not os.path.exists(os.path.join(args['worker_path'], args['username'])):
  53. os.makedirs(os.path.join(args['worker_path'], args['username']))
  54. start_all_services(client, os.path.join(args['worker_path'], args['username']))