-
Notifications
You must be signed in to change notification settings - Fork 0
/
_add_path.py
60 lines (49 loc) · 1.58 KB
/
_add_path.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Add ntlib directory or given path to sys.path (mylibs.pth in site-packages)."""
import os
import sys
__version__ = '0.1.1'
if __name__ != '__main__':
raise ImportError('this file must be executed directly')
#-------------------------------------------------------
if len(sys.argv) > 1:
pth = os.path.abspath(sys.argv[1])
else:
pth = os.path.dirname(os.path.abspath(__file__))
try:
import ntlib
raise SystemExit('ntlib already accessible')
except ImportError:
pass
pth, tail = os.path.split(pth)
if tail != 'ntlib':
raise SystemExit('ntlib not found')
if pth in sys.path:
raise SystemExit(f'location already in sys.path: {pth}')
if not os.path.isdir(pth):
raise SystemExit(f'directory not found: {pth}')
print(f'add location {pth}')
def update_pth(filename: str) -> None:
newline = False
if os.path.exists(filename):
with open(filename, 'r') as f:
s = f.read()
if s:
for i in s.split('\n'):
if i and os.path.abspath(i) == pth:
raise SystemExit(f'location already in {filename}')
if s[-1] != '\n':
newline = True
with open(filename, 'a') as f:
if newline:
f.write('\n')
f.write(pth + '\n')
raise SystemExit(f'successfully added location to {filename}')
package_paths = [p for p in sys.path if os.path.basename(p) == 'site-packages']
package_paths.extend(p for p in sys.path if os.path.basename(p) == 'dist-packages')
for p in package_paths:
filename = os.path.join(p, 'mylibs.pth')
try:
update_pth(filename)
except PermissionError:
print(f'no permission to add location to {filename}')
raise SystemExit('failed to add location to sys.path')