Coverage for /Users/Newville/Codes/xraylarch/larch/utils/paths.py: 53%

59 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-11-09 10:08 -0600

1import sys 

2import os 

3import platform 

4 

5HAS_PWD = True 

6try: 

7 import pwd 

8except ImportError: 

9 HAS_PWD = False 

10 

11def unixpath(d): 

12 return d.replace('\\', '/') 

13 

14def winpath(d): 

15 "ensure path uses windows delimiters" 

16 if d.startswith('//'): d = d[1:] 

17 d = d.replace('/','\\') 

18 return d 

19 

20# uname = 'win', 'linux', or 'darwin' 

21uname = sys.platform.lower() 

22nativepath = unixpath 

23 

24if os.name == 'nt': 

25 uname = 'win' 

26 nativepath = winpath 

27if uname.startswith('linux'): 

28 uname = 'linux' 

29 

30# bindir = location of local binaries 

31nbits = platform.architecture()[0].replace('bit', '') 

32topdir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0] 

33bindir = os.path.abspath(os.path.join(topdir, 'bin', '%s%s' % (uname, nbits))) 

34 

35def get_homedir(): 

36 "determine home directory" 

37 homedir = None 

38 def check(method, s): 

39 "check that os.path.expanduser / expandvars gives a useful result" 

40 try: 

41 if method(s) not in (None, s): 

42 return method(s) 

43 except: 

44 pass 

45 return None 

46 

47 # for Unixes, allow for sudo case 

48 susername = os.environ.get("SUDO_USER", None) 

49 if HAS_PWD and susername is not None and homedir is None: 

50 homedir = pwd.getpwnam(susername).pw_dir 

51 

52 # try expanding '~' -- should work on most Unixes 

53 if homedir is None: 

54 homedir = check(os.path.expanduser, '~') 

55 

56 # try the common environmental variables 

57 if homedir is None: 

58 for var in ('$HOME', '$HOMEPATH', '$USERPROFILE', '$ALLUSERSPROFILE'): 

59 homedir = check(os.path.expandvars, var) 

60 if homedir is not None: 

61 break 

62 

63 # For Windows, ask for parent of Roaming 'Application Data' directory 

64 if homedir is None and os.name == 'nt': 

65 try: 

66 from win32com.shell import shellcon, shell 

67 homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) 

68 except ImportError: 

69 pass 

70 

71 # finally, use current folder 

72 if homedir is None: 

73 homedir = os.path.abspath('.') 

74 return nativepath(homedir) 

75 

76def get_cwd(): 

77 """get current working directory 

78 Note: os.getcwd() can fail with permission error. 

79 

80 when that happens, this changes to the users `HOME` directory 

81 and returns that directory so that it always returns an existing 

82 and readable directory. 

83 """ 

84 try: 

85 return os.getcwd() 

86 except: 

87 home = get_homedir() 

88 os.chdir(home) 

89 return home