ini_op.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. #author: lingyue.wkl
  4. #desc: use to read ini
  5. #---------------------
  6. #2012-02-18 created
  7. #2012-09-02 changed for class support
  8. #---------------------
  9. import sys,os,time
  10. import configparser
  11. class Config:
  12. def __init__(self, path):
  13. self.path = path
  14. self.cf = configparser.ConfigParser()
  15. self.cf.read(self.path)
  16. def get(self, field, key):
  17. result = ""
  18. try:
  19. result = self.cf.get(field, key)
  20. except:
  21. result = ""
  22. return result
  23. def set(self, filed, key, value):
  24. try:
  25. self.cf.set(field, key, value)
  26. self.cf.write(open(self.path,'w'))
  27. except:
  28. return False
  29. return True
  30. def read_config(config_file_path, field, key):
  31. cf = configparser.ConfigParser()
  32. try:
  33. cf.read(config_file_path)
  34. result = cf.get(field, key)
  35. except:
  36. sys.exit(1)
  37. return result
  38. def write_config(config_file_path, field, key, value):
  39. cf = configparser.ConfigParser()
  40. try:
  41. cf.read(config_file_path)
  42. cf.set(field, key, value)
  43. cf.write(open(config_file_path,'w'))
  44. except:
  45. sys.exit(1)
  46. return True
  47. if __name__ == "__main__":
  48. if len(sys.argv) < 4:
  49. sys.exit(1)
  50. config_file_path = sys.argv[1]
  51. field = sys.argv[2]
  52. key = sys.argv[3]
  53. if len(sys.argv) == 4:
  54. print(read_config(config_file_path, field, key))
  55. else:
  56. value = sys.argv[4]
  57. write_config(config_file_path, field, key, value)