Coverage for larch/utils/shellutils.py: 29%
70 statements
« prev ^ index » next coverage.py v7.6.0, created at 2024-10-16 21:04 +0000
« prev ^ index » next coverage.py v7.6.0, created at 2024-10-16 21:04 +0000
1#!/usr/bin/env python
2"""
3 Larch shell utilities:
4 more()
5 ls()
6 cwd()
7 cd()
8"""
10import os
11import sys
12from glob import glob
13from .paths import get_cwd
15def _parent(name, _larch=None):
16 "return parent group name of an object"
17 return _larch.symtable._lookup(name)
19def ls(directory='.'):
20 """return a list of files in the current directory,
21 optionally using '*' to match file names
23 Returns
24 -------
25 a : list of strings
26 matching file names
28 Examples
29 --------
30 to list all files::
32 larch> ls('.')
34 to list all files that end with '.xdi'::
36 larch> ls('*.xdi')
39 """
40 directory.strip()
41 if len(directory) == 0:
42 arg = '.'
43 if os.path.isdir(directory):
44 ret = os.listdir(directory)
45 else:
46 ret = glob(directory)
47 if sys.platform.startswith('win'):
48 for i in range(len(ret)):
49 ret[i] = ret[i].replace('\\','/')
50 return ret
52def cwd():
53 "return current working directory"
54 ret = get_cwd()
55 if sys.platform.startswith('win'):
56 ret = ret.replace('\\','/')
57 return ret
59def cd(name):
60 """change directory to specified directory"""
61 os.chdir(name.strip())
62 return cwd()
65def mkdir(name, mode=0o775):
66 """create directory (and any intermediate subdirectories)
68 Options:
69 --------
70 mode permission mask to use for creating directory (default=0775)
71 """
72 if os.path.exists(name):
73 if os.path.isdir(name):
74 os.chmod(name, mode)
75 else:
76 raise FileExistsError(f"'{name}' is a file, cannot make folder with that name")
77 else:
78 os.makedirs(name, mode=mode)
81def show_more(text, filename=None, writer=None,
82 pagelength=30, prefix='', _larch=None):
83 """show lines of text in the style of more """
84 txt = text[:]
85 if isinstance(txt, str):
86 txt = txt.split('\n')
87 if len(txt) <1:
88 return
89 prompt = '== hit return for more, q to quit'
90 ps = "%s (%%.2f%%%%) == " % prompt
91 if filename:
92 ps = "%s (%%.2f%%%% of %s) == " % (prompt, filename)
94 if writer is None:
95 writer = sys.stdout
97 i = 0
98 for i in range(len(txt)):
99 if txt[i].endswith('\n'):
100 _larch.writer.write("%s%s" % (prefix, txt[i]))
101 else:
102 writer.write("%s%s\n" % (prefix, txt[i]))
103 i = i + 1
104 if i % pagelength == 0:
105 try:
106 x = input(ps % (100.*i/len(txt)))
107 if x in ('q','Q'): return
108 except KeyboardInterrupt:
109 writer.write("\n")
110 return
112def _more(fname, pagelength=32, _larch=None):
113 """list file contents:
114 > more('file.txt')
115by default, the file is shown 32 lines at a time.
116You can specify the number of lines to show at a time
117with the pagelength option:
118 > more('file.txt', pagelength=10)
119 """
120 output = _larch.writer.write
121 if not os.path.exists(fname):
122 output("File '%s' not found.\n" % fname)
123 return
125 elif not os.path.isfile(fname):
126 output("'%s' not a file.\n" % fname)
127 return
129 try:
130 text = open(fname, 'r').readlines()
131 except IOError:
132 output("cannot open file: %s\n" % fname)
133 return
135 show_more(text, filename=fname, _larch=_larch,
136 pagelength=pagelength)