environment_switch.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2021/5/27 11:23
  3. # @Author : XuJiakai
  4. # @File : environment_switch
  5. # @Software: PyCharm
  6. import platform
  7. import subprocess
  8. import os
  9. import yaml
  10. _module_path = os.path.dirname(__file__)
  11. def __ping_judge(ip):
  12. CREATE_NO_WINDOW = 0x08000000
  13. win_ping_cmd = "ping -n 1 {}".format(ip)
  14. linux_ping_cmd = "ping -c 1 {}".format(ip)
  15. if platform.system() == "Windows":
  16. ret = subprocess.call(win_ping_cmd, shell=True, creationflags=CREATE_NO_WINDOW)
  17. if platform.system() == "Linux":
  18. ret = subprocess.call(linux_ping_cmd, shell=True)
  19. if ret == 0:
  20. return True
  21. if ret == 1:
  22. return False
  23. def _is_intranet_env():
  24. if platform.system() == "Windows":
  25. return False
  26. # return __ping_judge("oss-cn-shanghai-internal.aliyuncs.com")
  27. return True
  28. class environment_switch:
  29. def __init__(self):
  30. self.is_intranet = _is_intranet_env()
  31. self.config = self.__get_conf()
  32. pass
  33. def __get_conf(self):
  34. if self.is_intranet:
  35. f = open(os.path.join(_module_path, 'env-prod.yaml')) # 打开yaml文件
  36. pass
  37. else:
  38. f = open(os.path.join(_module_path, 'env-dev.yaml')) # 打开yaml文件
  39. pass
  40. d = yaml.load(f, Loader=yaml.FullLoader) # 使用load方法加载
  41. return d
  42. def get_val(self, path):
  43. return self.__get_val(self.config, path)
  44. def __get_val(self, conf, path):
  45. index = path.find('.')
  46. if index == -1 and path in conf:
  47. return conf[path]
  48. k = path[0: index]
  49. other_path = path[index + 1:]
  50. if k in conf:
  51. v = conf[k]
  52. return self.__get_val(v, other_path)
  53. return None
  54. project_env = environment_switch()
  55. if __name__ == '__main__':
  56. env = environment_switch()
  57. print(env.is_intranet)
  58. # vv = env.get_val('mongo.itslaw.url')
  59. # print(vv)
  60. pass