PoserIni2.py
1    from __future__ import print_function
2    
3    import \
4        os, \
5        errno, \
6        wx
7    
8    try:
9        from wx import NotificationMessage
10   except ImportError:
11       from wx.adv import NotificationMessage
12   
13   try:
14       import poser
15   except ImportError:
16       import POSER_FAKE as poser
17   
18   INIFILE = os.path.join(poser.PrefsLocation(), "Poser.ini")
19   PoserIni = type("PoserIni", (object,), dict())
20   
21   
22   def read_inifile(timeout=0):
23       if os.access(INIFILE, os.R_OK):
24           order = list()
25           try:
26               with open(INIFILE, "r") as fh:
27                   for line in fh:
28                       line = line.strip()
29                       if not line or line.startswith("#"):
30                           continue
31   
32                       k, _, v = line.partition(" ")
33                       order.append(k.strip())
34                       setattr(PoserIni, k.strip(), v.strip())
35           except IOError as err:
36               if err.errno == errno.ETXTBSY and timeout > 0:
37                   wx.CallLater(1000, read_inifile, [], timeout=timeout - 1)
38               else:
39                   m = NotificationMessage(title="PoserIni.py", message="Can't read '%s'." % INIFILE)
40                   m.SetFlags(wx.ICON_ERROR)
41                   m.Show(timeout=NotificationMessage.Timeout_Auto)
42   
43           # Other errors are allowed to interrupt the script.
44   
45           PoserIni.__order__ = order
46   
47   
48 def save_inifile(): 49 if os.access(INIFILE, os.W_OK): 50 try: 51 with open(INIFILE, "w") as fh: 52 for arg in PoserIni.__order__: 53 print(arg, getattr(PoserIni, arg), file=fh) 54 except IOError as err: 55 if err.errno == errno.ETXTBSY: 56 wx.CallLater(300, save_inifile) 57 m = NotificationMessage(title="PoserIni.py", message="Delayed write to Poser.ini.") 58 m.SetFlags(wx.ICON_INFORMATION) 59 m.Show(timeout=NotificationMessage.Timeout_Auto) 60 else: 61 m = NotificationMessage(title="PoserIni.py", message="Can't write '%s'." % INIFILE) 62 m.SetFlags(wx.ICON_ERROR) 63 m.Show(timeout=NotificationMessage.Timeout_Auto) 64 except Exception as err: 65 m = NotificationMessage(title="PoserIni.py", message="Error writing Poser.ini: '%s'." % err) 66 m.SetFlags(wx.ICON_ERROR) 67 m.Show(timeout=NotificationMessage.Timeout_Auto) 68 69 else: 70 m = NotificationMessage(title="PoserIni.py", message="No permission to write Poser.ini.") 71 m.SetFlags(wx.ICON_ERROR) 72 m.Show(timeout=NotificationMessage.Timeout_Auto) 73 74
75 def UpdateIni(key=None, value=None): 76 """ 77 Short form for: 78 PoserIni.<key> = <value> 79 save_inifile() 80 """ 81 if key and hasattr(PoserIni, key): 82 setattr(PoserIni, key, value) 83 save_inifile() 84 85 86 read_inifile(10) 87