def showCentered(expr, ssize=None): half = " " * ceil((get_terminal_size().columns - (size if ssize == None else size)) / 2) expr = " " * ceil((ssize - len(expr)) / 2) + expr if ssize else expr print(f'{half}{expr}{half}')
def _determine_size(): """ Determines the attached terminal size through operating system calls. Tries to determine the size of the controlling terminal. If none is available, tries the connected standard streams to see if any is a terminal. @see `get_size()`. @rtype `os.terminal_size`. @raise RuntimeError The terminal size could not be determined. """ # Try to get the terminal size from the controlling terminal. try: tty = open("/dev/tty") except OSError: pass else: with closing(tty): return os.get_terminal_size(tty.fileno()) # No controlling terminal. Try each of stdin/stdout/stderr in succession. for file in sys.stdin, sys.stdout, sys.stderr: try: return os.get_terminal_size(file.fileno()) except OSError: pass # Give up. raise RuntimeError("can't determine terminal size")
def __init__(self, **kwargs): self.displayColumns = os.get_terminal_size().columns self.displayLines = os.get_terminal_size().lines self.currTextPage = 0 self.totalTextPages = 0 self.currActionPage = 0 self.displayText = "Uninitialized Card Text" self.possibleActions = [] self.tw = textwrap.TextWrapper(self.displayColumns) self.textBlockSize = self.displayLines - 3 return super().__init__(**kwargs)
def display_matches(self, substitution, matches, longest_match_length): line_buffer = readline.get_line_buffer() print("") ll = 0 max_columns = 80 try: max_columns = os.get_terminal_size().columns except Exception: pass try: padding = max(len(m) for m in matches) + 2 for match in matches: s = match + (' ' * (padding - len(match))) ll += len(s) if ll > max_columns: print("") ll = len(s) printc(s, color="yellow", end='') except Exception: import traceback traceback.print_exc() print("\n> ", end="") print(line_buffer, end="") sys.stdout.flush()
def view_ior(test): retry = False n = 0 num = test.num m = " problempage:[P]" m = m if g_browser else "" while 1: i = test.filelist[n] tw, th = os.get_terminal_size() w = tw // 3 - 1 h = th - 6 lin = to_list(test.data[i][2], w, h) lout = to_list(test.data[i][3], w, h) lprg = to_list(test.data[i][4], w, h) os.system(g_cls) print(test.data[i][0], test.data[i][1]) print(" ".join([limitstr("data_in", w), limitstr("data_out", w), limitstr("program_output", w)])) for y in range(h): print("|".join([lin[y], lout[y], lprg[y]])) print("-"*(tw-1)) print(limitstr("next:[ENTER]" + m + " retry:[R]" + " quit:[Q]", w*2+2) + limitstr(i, w)) c = g_getch() if c == "\r": n = (n+1) % len(test.filelist) if c == "q": break if c == "r": retry = True break if c == "p" and m: Popen([g_browser, "https://yukicoder.me/problems/no/" + num]) return retry
def terminal_width(stdout): if hasattr(os, 'get_terminal_size'): # python 3.3 onwards has built-in support for getting terminal size try: return os.get_terminal_size().columns except OSError: return None try: # winsize structure has 4 unsigned short fields winsize = b'\0' * struct.calcsize('hhhh') try: winsize = ioctl(stdout, termios.TIOCGWINSZ, winsize) except IOError: return None except TypeError: # this is raised in unit tests as stdout is sometimes a StringIO return None winsize = struct.unpack('hhhh', winsize) columns = winsize[1] if not columns: return None return columns except IOError: return None
def main(): width = 80 # default width height = 24 # default height terminal_info = {} # dictionary to receive terminal info from system mode = None # variable to hold recommendation mode user_id = None # variable to hold user_id of user terminal_info = get_terminal_size() if terminal_info[0] > 0: width = terminal_info[0] if terminal_info[1] > 0: height = terminal_info[1] print('Initializing data structures from MovieLens files . . . ', end='') init_structures() print('complete.\n') print_welcome(width, height) while True: print('\nMain Menu: Enter number of selection or [Q] to quit\n' ' [1] User-Specific (requires userID)\n' ' [2] Pure Popular Movies') mode = get_mode() if mode == 1: user_id = get_user_id(width) user_loop(user_id, width, height) elif mode == 2: pop_loop(width, height) elif mode == 'q': print_goodbye(width) break
def eprint(string): """erase and print""" if sys.version_info >= (3,3): w = os.get_terminal_size()[0] print(' '*w, end='\r') print(string, end='\r') sys.stdout.flush()
def threadedUpdate(self = None): while not self.finished: try: self.barMaxLength = os.get_terminal_size(self.out.fileno()).columns - self.difTermAndBar if self.barMaxLength < 0: self.barMaxLength = 0 except OSError: self.barMaxLength = 80 - self.difTermAndBar except AttributeError: #Pypy fallback self.barMaxLength = 80 - self.difTermAndBar self.out.write('\r') percentString = '{:.1%}'.format(self.per).rjust(self.percLength, ' ') barLength = int(self.per * self.barMaxLength) if self.big and self.inputString: self.dString = self.prepString(self.inputString, self.barMaxLength + self.difTermAndBar - self.timeLength) + self.prepTime(time.time() - self.sTime, self.timeLength) if barLength >= self.barMaxLength: self.out.write('[' + '=' * barLength + ']' + percentString) self.out.write('\n' + self.dString + '\033[F') else: self.out.write('[' + '=' * barLength + '>' + ' ' * (self.barMaxLength - barLength - 1) + ']' + percentString) self.out.write('\n' + self.dString + '\033[') elif self.inputString: self.dString = self.prepString(self.inputString, self.barMaxLength + self.difTermAndBar - self.timeLength - self.percLength - 2) + '[' + self.prepTime(time.time() - self.sTime, self.timeLength) + ']' + percentString self.out.write(self.dString) else: if barLength >= self.barMaxLength: self.out.write('[' + '=' * barLength + ']' + percentString + '\r') else: self.out.write('[' + '=' * barLength + '>' + ' ' * (self.barMaxLength - barLength - 1) + ']' + percentString + '\r') self.out.flush() time.sleep(.1)
def makeTitle(): sz = os.get_terminal_size() sz = float(sz.columns) os.system("clear") print("-" * int(sz)) print(" " * int(0.5 * (sz - (len(PName)))) + PName + " " * int(0.5 * (sz - (len(PName))))) print("-" * int(sz))
def __init__(self, wcdir, importdir, svninfo): cmd.Cmd.__init__(self) self.wcdir = wcdir self.importdir = importdir self.svninfo = svninfo self.config = Config() self.config.add_option('save-diff-copied', ConfigOpt(None, "Save 'svn diff' output on the " + "moved/copied files and directories to this " + "file as part of 'apply'")) self.config.add_option('dir-similarity', ConfigOptInt(600, "Similarity between dirs to assume " + "a copy/move [0..1000]")) self.config.add_option('file-similarity', ConfigOptInt(600, "Similarity between files to assume a " + "copy/move [0..1000]")) self.config.add_option('file-min-lines', ConfigOptInt(10, "Minimal number of lines in a file for " + "meaningful comparison")) self.config.add_option('verbose', ConfigOptInt(3, "Verbosity of the output [0..5]")) try: self.termwidth = os.get_terminal_size()[0] except OSError: # Not running in a terminal - probably redirected to file self.termwidth = 150 # arbitrary number
def finish(self, inputString): if not self.dummy: self.finished = True self.inputString = str(inputString) self.ioThread.join() try: self.barMaxLength = os.get_terminal_size(self.out.fileno()).columns - self.difTermAndBar if self.barMaxLength < 0: self.barMaxLength = 0 except OSError: self.barMaxLength = 80 - self.difTermAndBar except AttributeError: #Pypy fallback self.barMaxLength = 80 - self.difTermAndBar if self.big: self.out.write('\n' + ' ' * (self.barMaxLength + self.difTermAndBar) + '\033[F') else: self.out.write('\r') if len(self.inputString) < self.barMaxLength + self.difTermAndBar - self.timeLength: tString = self.prepTime(time.time() - self.sTime, self.barMaxLength + self.difTermAndBar - len(self.inputString) - 1) self.out.write(self.inputString + ' ' + tString) else: self.out.write(self.prepString(self.inputString, self.barMaxLength + self.difTermAndBar - self.timeLength) + self.prepTime(time.time() - self.sTime, self.timeLength)) self.out.write('\n') self.out.flush()
def get_display_width(): """Get the maximum display width to output.""" if PY2: # Python 2 does not have get_terminal_size, so just get it fron # the environment variable and fallback to 80 return int(os.environ.get('COLUMNS', 80)) else: # On Python 3, we can use the entire width of the terminal return os.get_terminal_size().columns
def __init__(self, totalsize, preprocessed=0, interval=1.0, speed_mode="cumulative"): """Initialize the ProgressBar class. See class docstring for parameters of the constructor. """ if totalsize <= 0: raise ValueError("total size must be positive; got %d" % totalsize) super().__init__(interval=interval, show_elapsed_time=False) self.totalsize = totalsize self.processed = preprocessed self.preprocessed = preprocessed self.speed_mode = speed_mode self._last_processed = 0 # calculate bar length try: ncol, _ = os.get_terminal_size() except (AttributeError, OSError): # Python2 do not have os.get_terminal_size. Also, # os.get_terminal_size fails if stdout is redirected to a # pipe (pretty stupid -- should check stderr; relevant # Python bug: https://bugs.python.org/issue14841). In either # case, Assume a minimum of 80 columns. ncol = 80 self._barlen = (ncol - 48) if ncol >= 58 else 10 super().text(self._generate_bar, force=True)
def main(scr): scr.clear() width, height = os.get_terminal_size() s = '' x, y = 0, 0 while True: k = scr.getch() if k < 127: s += chr(k) if s[-1] == '\n': break else: if x >= width: y += 1 x = 0 scr.addch(y, x, s[-1]) x += 1 scr.refresh() elif k == 127 and (x > 0 or y > 0) and s: *s, _ = s if x > 0: x -= 1 else: x = width - 1 y -= 1 scr.addch(y, x, ' ') scr.move(y, x) scr.refresh() scr.clear() scr.addstr(0, 0, s) scr.getch()
def printYaks(yaks,yakwindow): yakwindow.clear(); yakwindow.border(0); sz = os.get_terminal_size(); yakwindow.addstr(0,math.floor(sz.columns/2)-3,"Yaks"); currentLine = 1; i = 0; yakSpace = sz.columns-11; while (i < len(yaks)) and (currentLine < sz.lines-9): yakLines = list(); yak = yaks[i]; if (yak["type"] != 0): yak["message"] = yak["message"]+ " [image]"; n = 0; while (n < len(yak["message"])): if (n+yakSpace < len(yak["message"])): yakLines.append(yak["message"][n:n+yakSpace]); else: yakLines.append(yak["message"][n:len(yak["message"])]); n += yakSpace; yakwindow.addstr(currentLine,sz.columns-7,str(math.floor(float(yak["score"])))); for messageLine in yakLines: yakwindow.addstr(currentLine,2,messageLine); currentLine += 1; i += 1; printYakarma(yakwindow);
def hhistplot(counter, highlighted, indent = "", pipe = sys.stdout, w = 20): BLOCK = "█" LEFT_HALF_BLOCK = "▌" try: W, H = os.get_terminal_size() except (OSError, AttributeError): W, H = 80, 24 plot_w = min(w, W - 10 - len(indent)) scale = plot_w / max(counter.values()) data = sorted(counter.items()) if highlighted != None and highlighted not in counter: bisect.insort_left(data, (highlighted, 0)) header_width = max(len(str(value)) for _, value in data) for key, value in data: label = str(key) bar_size = int(value * scale) header = indent + "[" + str(value).rjust(header_width) + "] " bar = (BLOCK * bar_size if bar_size > 0 else LEFT_HALF_BLOCK) + " " label_avail_space = W - 2 - len(bar) - len(header) if len(label) > label_avail_space: label = label[:label_avail_space - 3] + "..." line = bar + label if key == highlighted: line = color.highlight(line, color.term.PLAIN, color.term.RED) pipe.write(header + line + "\n")
def selected(param): """Affiche les groupes sélectionnées en vert la machine est allumée en mauve la machine est allumée mais n'a pas de tag_file (elle a du être re-installée) ou elle contient un tag plus ancien que le dernier tag utilisé en gris la machine est éteinte en rouge la machine a un message d'erreur (utiliser errors pour l'afficher) Pour différencier les machines sans tag de celle avec un vieux tag il faut utiliser l'option tagview qui permet de mettre en rouge les machine sans tag et en mauve celles qui ont un vieux tag Usage: selected [help] [tagview] """ doc = selected.__doc__ arg = docopt2.docopt(doc, argv=param, help=False) notag = False if arg['help']: return print(doc) if var_global.selected_groupes == []: print('Auncun groupe sélectionné') else: print('-' * (os.get_terminal_size().columns - 1)) if arg['tagview']: notag = True print("\n".join([g.str_groupe(notag) for g in var_global.selected_groupes]).strip()) return
def frame(): (width, height) = os.get_terminal_size() height -= 3 stats = ( "HP:" + str(health) + "|GOLD:" + str(money) + "|HOME:" + str(home.x) + "," + str(home.y) + "|LOCATION:" + str(location.x) + "," + str(location.y) ) remcols = width - len(stats) stats = "=" * (remcols // 2) + stats + "=" * (remcols // 2) + "=" * (remcols % 2) print(stats) inv = "INVENTORY:" + "|".join( list(map(lambda x: "@" + dispitem(x) if RLE(INVENTORY).index(x) == CURINDEX else dispitem(x), RLE(INVENTORY))) ) remcols = width - len(inv) inv = "=" * (remcols // 2) + inv + "=" * (remcols // 2) + "=" * (remcols % 2) print(inv) wt = "WEIGHT:" + str(INVWEIGHT) + "|MAX WEIGHT:" + str(MAXWEIGHT) remcols = width - len(wt) wt = "=" * (remcols // 2) + wt + "=" * (remcols // 2) + "=" * (remcols % 2) print(wt) for y in range(height): for x in range(width): print(GetMap(x)(y), end="")
def print_msg(): while not STOP_ME: try: msg = msg_queue.get(timeout=0.1) sys.stdout.write('\r'+msg.ljust(os.get_terminal_size().columns)+'\n') except: continue
def get_terminal_width(): size = 0 try: size = os.get_terminal_size().columns except (AttributeError, OSError): pass return size if size > 20 else 78
def __init__(self, fps = 24, # number of frames per second dropDensity = 0.07, # how many new drops will appear each second (arbitrary value) dropSpeedRange = (15, 35), # the minimum and maximum speed that a drop may fall at in lines per second dropPersistenceRange = (0.5, 5), # the minimum and maximum time that a drop may keep pouring before falling chanceDropNotOnTop = 0.33, # the chance a drop has not to appear at the very top of the screen (0 beeing 0 percent and 1 beeing 100 percent) dropHeightRangePop = (0.25, 0.75)): # the minimum and maximum portion of the screen on the Y axis, that a drop may appear at (0 beeing 0 percent and 1 beeing 100 percent) self.width, self.height = get_terminal_size() self.frameDuration = 1 / fps self.dropDensity = dropDensity / fps # dividing by fps to keep the same rate of appearance since the process of drop creation is handled on a frame basis rather than a time basis self.dropSpeedRange = dropSpeedRange self.dropPersistenceRange = dropPersistenceRange self.chanceDropNotOnTop = chanceDropNotOnTop tmpMin = floor(dropHeightRangePop[0] * self.height) tmpMax = floor(dropHeightRangePop[1] * self.height) self.dropHeightRangePop = (tmpMin, tmpMax) self.dropList = [] self.randomString = '' # to minimize the number of calls to a random function (which are quite time consuming), we choose to iterate over a single randomized string when composing the frame self.rsl = 1000 # the length of the string self.rsc = 0 # the index counter of the string myPrintable = string.ascii_letters + string.digits + string.punctuation for i in range(self.rsl): self.randomString += choice(myPrintable) self.pixels = [] # nested arrays of booleans representing if a pixel is blank or not for x in range(self.width): self.pixels.append([]) for y in range(self.height): self.pixels[x].append(False)
def clear(): #PARA LIMPAR TELA DO TERMINAL try: import os lines = os.get_terminal_size().lines except AttributeError: lines = 130 print("\n" * lines)
def sigwinch_handler(sig=signal.SIGWINCH, frame=None): """Handle window resize signal""" global PRINT_INFO if sys.version[0] == 3: PRINT_INFO['cols'] = os.get_terminal_size()[0] else: PRINT_INFO['cols'] = tput('cols', 1)
def generate(self,x,y): table = [] pointlist = self.generatepoints(x,y) self.pointlist=pointlist for i in range(y): eks = [] for j in range(x): for (xp,yp,off) in pointlist: if i in range(yp-off+1,yp+off): if j in range(xp-off+1,xp+off): eks.append(' ') if i==yp-off or i==yp+off: if j==xp-off or j==xp+off: eks.append('#') if len(eks)!=j+1: eks.append('#') table.append(eks) carvetable=self.carve(pointlist) for i in range(len(pointlist)): nonewcorridor=True while nonewcorridor: for j in carvetable[i][1:]: k=random.randint(0,1) if k: (xp,yp,off)=pointlist[i] (xp2,yp2,off2)=pointlist[j] if xp2>xp: for k in range(xp,xp2): table[k][yp]=' ' elif xp>xp2: for k in range(xp2,xp): table[k][yp]=' ' elif yp>yp2: for k in range(yp2,yp): table[xp][k]=' ' elif yp2>yp: for k in range(yp,yp2): table[xp][k]=' ' nonewcorridor=False startpos=pointlist[random.randint(0,63)] endpos=pointlist[random.randint(0,63)] while endpos==startpos: endpos=pointlist[random.randint(0,63)] (ex,ey,eoff)=endpos table[ex][ey]="/" self.environment=table current_os=platform.system() if current_os=='Windows': sz=os.get_terminal_size() self.rows=sz.lines self.columns=sz.columns else: self.rows, self.columns = os.popen('stty size', 'r').read().split() self.rows=int(self.rows)#-self.row_offset*2 self.columns=int(self.columns)#-self.column_offset*2""" self.row_offset=1 self.column_offset=10 (sx,sy,soff)=startpos return (sx,sy)
def progress_bar(requests, loop, freq=0.01): width, _ = get_terminal_size() done_count = len(tuple(filter(lambda t: t.done(), Task.all_tasks()))) tasks_left_count = requests - done_count progress = int(done_count / requests * width) print("\r" + "*" * progress + "." * (width - progress), end="") if tasks_left_count > 0: loop.call_later(freq, progress_bar, requests, loop)
def _get_terminal_size_linux(): try: return tuple(os.get_terminal_size()) except: try: return (os.environ['LINES'],os.environ['COLUMNS']) except: return (80,25)
def _get_term_width(self): try: return int(os.environ["COLUMNS"]) except (KeyError, ValueError): try: return os.get_terminal_size(self._output.fileno()).columns except OSError: return None
def get_terminal_width(): """Return the width of the terminal""" try: width = os.get_terminal_size().columns except: #if any error occurs when getting the screen width, just use 70 as the width width = 70 return width
def download_into_with_progressbar(url, dest): import time from functools import partial from termutils import download_process, get_terminal_size w = os.get_terminal_size()[1] with open(dest, "wb") as f: download_into(requests, url, f, partial(download_process, dest, time.time(), width=w))
def new_board(custom_size): import os if custom_size is None: termsize = os.get_terminal_size() maxx, maxy = termsize.columns - 1, termsize.lines - 1 else: maxx, maxy = custom_size[0], custom_size[1] return {(x, y): DEAD for x in range(maxx) for y in range(maxy)}
def separator(color, char, l): if l: return columns, rows = os.get_terminal_size(0) for i in range(columns): print(color + char, end="" + Output.RESET) print("\n")
from fonctions import masseVolumiqueLEau, presionVapeurSaturante, table, \ viscositeDynamique from openpyxl import load_workbook from numpy import array, concatenate, empty, linspace, shape from constantes import codenames_sheets, livreExcel, M_l, noms_donnees, R import os __all__ = [ 'L', 'J', 'T', 'N', 'erreur_max', 'h_all_0', 'h_all_1_0', 'condLim', 'condLim_0_all', 'condLim_L_all', 'temp', 'p_l', 'n_l', 'Pvsat', 'M_l', 'R', 'phi', 'Sr', 'k_l', 'm', 'D_0', 'A', 'B' ] # Declaration de variables ts = os.get_terminal_size() # : dimensions de la terminal larguer_terminal = ts.columns # : larguer de la terminal # Début : mettre les données du problème # # Charger données du fichier Données.xlsm strTexte = "Chargement les données du fichier" print(strTexte.center(larguer_terminal, '*')) # Ouvrir le livre Données.xlsm wb = load_workbook( filename=livreExcel, # livre d'Excel à ouvrir read_only=True, # seulement lire, on peut pas modifier data_only=True) # lire les valeurs des cellules # Mettre les données
def show_dirs(path=os.getcwd()): """ Prints the files and directories in the specified path in column This function prints the files and folders in equally sapced columns according to the screen width Parameters: path (str): Path of the directory (default = os.getcwd()) Returns: None """ print(color["blue"] + "Contents of the current directory") filelist = os.listdir(path) filelist.sort(key=lambda x: x.lower()) # index padding ind = len(filelist) if ind >= 1000: ind = 4 elif ind >= 100: ind = 3 elif ind >= 10: ind = 2 else: ind = 1 scr_width = int(os.get_terminal_size()[0]) try: mlen = (max( len(word) + 1 if os.path.isdir(word) else len(word) for word in filelist) + 1) except ValueError: mlen = 1 cols = scr_width // mlen if scr_width < mlen: mlen = scr_width line = "" lst = [] for count, _file in enumerate(filelist, start=1): last = True # last line # directories(cyan) if os.path.isdir(path + os.sep + _file): _file = _file + os.sep st = "[{0:>{ind}}] {1:<{mlen}}".format(str(count), _file, mlen=mlen, ind=ind) if scr_width - (abs(len(line) - cols * 5) % scr_width) > len(st): line = line + color["cyan"] + st else: lst.append(line) line = color["cyan"] + st last = False # executeable files(yellow) elif os.access(path + os.sep + _file, os.X_OK): st = "[{0:>{ind}}] {1:<{mlen}}".format(str(count), _file, mlen=mlen, ind=ind) if scr_width - (abs(len(line) - cols * 5) % scr_width) > len(st): line = line + color["yellow"] + st else: lst.append(line) line = color["yellow"] + st last = False # other files(green) else: st = "[{0:>{ind}}] {1:<{mlen}}".format(str(count), _file, mlen=mlen, ind=ind) if scr_width - (abs(len(line) - cols * 5) % scr_width) > len(st): line = line + color["green"] + st else: lst.append(line) line = color["green"] + st last = False # append the last line to the list if last: lst.append(line) print("\n".join(lst))
s = "Look into my eyes, look into my eyes, the eyes, the eyes, \ the eyes, not around the eyes, don't look around the eyes, \ look into my eyes, you're under." import textwrap print(textwrap.fill(s, 70)) print(textwrap.fill(s, 40)) print(textwrap.fill(s, 40, initial_indent=' ')) print(textwrap.fill(s, 40, subsequent_indent=' ')) # Advanced import os os.get_terminal_size().columns
#!/usr/bin/env python3 from os import get_terminal_size, system from math import ceil from time import sleep import cursor hide_cursor, show_cursor = cursor.hide, cursor.show hide_cursor() minSize = 17 minSizeH = 7 Size = 16 size = ceil(get_terminal_size().columns * Size / 100) sizeH = ceil(get_terminal_size().lines * Size / 100) def clear(): system('clear') def logo(Size=16, Marg=0): size = ceil(get_terminal_size().columns * Size / 100) sizeH = ceil(get_terminal_size().lines * Size / 100) size = minSize if size < minSize else size sizeH = minSizeH if sizeH < minSizeH else sizeH def prctDeSize(prct, H=None): return ceil(prct * (size if H == None else sizeH) / 100) margin = prctDeSize(24) longT = prctDeSize(39)
import os import sys a = os.name print(a) # posix 又は nt と表示される b = sys.platform print(b) # OSの種類が表示される c = os.uname() # Unix交換OSのみ print(c.sysname) # Linux 等のOSの名前 print(c.nodename) # ip-172-31-8-41 等のネットワーク上の名 print(c.release) # 4.4.0-1069-aws 等のOSのバージョン print(c.version) # #79-Ubuntu SMP Mon Sep 24 等の詳細なバージョン print(c.machine) # x86_64 等のCPUの名前 d = os.getlogin() print(d) # OSのログインユーザー名が表示される e = os.get_terminal_size() print(e[0], e[1]) # コンソールのサイズが表示される f = os.getpid() print(f) # 実行中のプロセスIDが表示される g = os.getppid() print(g) # 親プロセスのプロセスIDが表示される h = os.getenv('HOME') os.putenv('PATH', '/') os.unsetenv('LD_PATH') i = os.environ['HOME'] os.environ['PATH'] = '/' del os.environ['LD_PATH']
def mainloop(self): '''Enters the main event loop and waits until :meth:`~quit` is called or the main widget is destroyed.''' TTkLog.debug("") TTkLog.debug(" ████████╗ ████████╗ ") TTkLog.debug(" ╚══██╔══╝ ╚══██╔══╝ ") TTkLog.debug(" ██║ ▄▄ ▄ ▄▄ ▄▄▖▄▖ ██║ █ ▗▖ ") TTkLog.debug(" ▞▀▚ ▖▗ ██║ █▄▄█ █▀▘ █ █ █ ██║ █▟▘ ") TTkLog.debug(" ▙▄▞▐▄▟ ██║ ▀▄▄▖ █ █ ▝ █ ██║ █ ▀▄ ") TTkLog.debug(" ▌ ▐ ╚═╝ ╚═╝ ") TTkLog.debug(" ▚▄▄▘ ") TTkLog.debug("") TTkLog.debug(f" Version: {TTkCfg.version}") TTkLog.debug("") TTkLog.debug("Starting Main Loop...") # Register events try: signal.signal(signal.SIGTSTP, self._SIGSTOP) # Ctrl-Z signal.signal(signal.SIGCONT, self._SIGCONT) # Resume signal.signal(signal.SIGINT, self._SIGINT) # Ctrl-C except Exception as e: TTkLog.error(f"{e}") exit(1) else: TTkLog.debug("Signal Event Registered") TTkTerm.registerResizeCb(self._win_resize_cb) threading.Thread(target=self._input_thread, daemon=True).start() self._timer = TTkTimer() self._timer.timeout.connect(self._time_event) self._timer.start(0.1) self.show() self.running = True # Keep track of the multiTap to avoid the extra key release lastMultiTap = False TTkTerm.init(title=self._title) while self.running: # Main Loop evt = self.events.get() if evt is TTkK.MOUSE_EVENT: mevt = self.mouse_events.get() # Avoid to broadcast a key release after a multitap event if mevt.evt == TTkK.Release and lastMultiTap: continue lastMultiTap = mevt.tap > 1 focusWidget = TTkHelper.getFocus() if focusWidget is not None and \ mevt.evt != TTkK.Press and \ mevt.key != TTkK.Wheel: x, y = TTkHelper.absPos(focusWidget) nmevt = mevt.clone(pos=(mevt.x - x, mevt.y - y)) focusWidget.mouseEvent(nmevt) else: # Sometimes the release event is not retrieved if focusWidget and focusWidget._pendingMouseRelease: focusWidget.mouseEvent(nmevt.clone(evt=TTkK.Release)) focusWidget._pendingMouseRelease = False self.mouseEvent(mevt) elif evt is TTkK.KEY_EVENT: keyHandled = False kevt = self.key_events.get() # TTkLog.debug(f"Key: {kevt}") focusWidget = TTkHelper.getFocus() overlayWidget = TTkHelper.getOverlay() TTkLog.debug(f"{focusWidget}") if focusWidget is not None: TTkHelper.execShortcut(kevt.key, focusWidget) keyHandled = focusWidget.keyEvent(kevt) else: TTkHelper.execShortcut(kevt.key) # Handle Next Focus Key Binding if not keyHandled and \ ((kevt.key == TTkK.Key_Tab and kevt.mod == TTkK.NoModifier) or ( kevt.key == TTkK.Key_Right )): TTkHelper.nextFocus(focusWidget if focusWidget else self) # Handle Prev Focus Key Binding if not keyHandled and \ ((kevt.key == TTkK.Key_Tab and kevt.mod == TTkK.ShiftModifier) or ( kevt.key == TTkK.Key_Left )): TTkHelper.prevFocus(focusWidget if focusWidget else self) elif evt is TTkK.TIME_EVENT: size = os.get_terminal_size() self.setGeometry(0, 0, size.columns, size.lines) TTkHelper.paintAll() self._timer.start(1 / TTkCfg.maxFps) self._fps() pass elif evt is TTkK.SCREEN_EVENT: self.setGeometry(0, 0, TTkGlbl.term_w, TTkGlbl.term_h) TTkLog.info(f"Resize: w:{TTkGlbl.term_w}, h:{TTkGlbl.term_h}") elif evt is TTkK.QUIT_EVENT: TTkLog.debug(f"Quit.") break else: TTkLog.error(f"Unhandled Event {evt}") break TTkTerm.exit()
def _get_console_width(): try: console_width = os.get_terminal_size(0)[0] except: console_width = 76 return console_width
def size_check(): term_size = os.get_terminal_size() rows = term_size.lines cols = term_size.columns return (rows >= 30 and cols >= 80)
def get_terminal_width(): try: return int(os.get_terminal_size(0)[0]) except OSError: return 80
import os import textwrap from termcolor import colored try: term_w, _ = os.get_terminal_size() except OSError: term_w = 45 APP_WIDTH = min(45, term_w) class GenericPrinter: @staticmethod def print_header(header_name: str): print(header_name.upper().center(APP_WIDTH, '_')) @staticmethod def print_line_break(): print('-' * APP_WIDTH) @staticmethod def print_tabbed(key: str, value: str): print(colored(key, attrs=["bold"]) + "\t" + value) @staticmethod def print_pair(key, value, color=None, attrs=None): if not attrs: attrs = ['bold'] left = str(key) + ':'
##第二章 2.16-2.20内容 #2.16 以指定列宽格式化字符串 #问题 你有一些长字符串,想以指定的列宽将它们重新格式化 # import textwrap # s = "Look into my eyes, look into my eyes, the eyes, the eyes, the eyes, not around the eyes, don't look around the eyes, \ look into my eyes, you're under." # print(textwrap.fill(s,60)) # print(textwrap.fill(s,10)) # print(textwrap.fill(s,50,subsequent_indent=' ')) # textwrap 模块对于字符串打印是非常有用的,特别是当你希望输出自动匹配终端 大小的时候。 # 你可以使用 os.get_terminal_size() 方法来获取终端的大小尺寸。 import os print(os.get_terminal_size().columns) #2.17 在字符串中处理 html 和 xml #问题 你想将 HTML 或者 XML 实体如 &entity; 或 &#code; 替换为对应的文本。再者, 你需要转换文本中特定的字符 (比如 <, >, 或 &)。 import html s = 'Elements are written as "<tag>text</tag>".' print(s) print(html.escape(s)) #2.18 字符串令牌解析 #问题 你有一个字符串,想从左至右将其解析为一个令牌流 #感觉不太常用 不知道什么是令牌化 略过 #2.19 实现一个简单的递归下降分析器 #问题 你想根据一组语法规则解析文本并执行命令,或者构造一个代表输入的抽象语法 树。如果语法非常简单,你可以自己写这个解析器,而不是使用一些框架。 #也不常用 而且都是编译原理的东东 略
def formato(self): print( "-" * os.get_terminal_size()[0])
def _sigWinCh(signum, frame): TTkTerm.width, TTkTerm.height = os.get_terminal_size() if TTkTerm._sigWinChCb is not None: TTkTerm._sigWinChCb(TTkTerm.width, TTkTerm.height)
def play(self, stream = 1): # Bug: # 光标定位转义编码不兼容 Windows if not self.charVideo: return if stream == 1 and os.isatty(sys.stdout.fileno()): self.streamOut = sys.stdout.write self.streamFlush = sys.stdout.flush elif stream == 2 and os.isatty(sys.stderr.fileno()): self.streamOut = sys.stderr.write self.streamFlush = sys.stderr.flush elif hasattr(stream, 'write'): self.streamOut = stream.write self.streamFlush = stream.flush breakflag = False def getChar(): nonlocal breakflag try: # 若系统为 windows 则直接调用 msvcrt.getch() import msvcrt except ImportError: import termios, tty # 获得标准输入的文件描述符 fd = sys.stdin.fileno() # 保存标准输入的属性 old_settings = termios.tcgetattr(fd) try: # 设置标准输入为原始模式 tty.setraw(sys.stdin.fileno()) # 读取一个字符 ch = sys.stdin.read(1) finally: # 恢复标准输入为原来的属性 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) if ch: breakflag = True else: if msvcrt.getch(): breakflag = True # 创建线程 getchar = threading.Thread(target=getChar) # 设置为守护线程 getchar.daemon = True # 启动守护线程 getchar.start() # 输出的字符画行数 rows = len(self.charVideo[0])//os.get_terminal_size()[0] for frame in self.charVideo: # 接收到输入则退出循环 if breakflag: break self.streamOut(frame) self.streamFlush() time.sleep(self.timeInterval) # 共 rows 行,光标上移 rows-1 行回到开始处 self.streamOut('\033[{}A\r'.format(rows-1)) # 光标下移 rows-1 行到最后一行,清空最后一行 self.streamOut('\033[{}B\033[K'.format(rows-1)) # 清空最后一帧的所有行(从倒数第二行起) for i in range(rows-1): # 光标上移一行 self.streamOut('\033[1A') # 清空光标所在行 self.streamOut('\r\033[K') if breakflag: self.streamOut('User interrupt!\n') else: self.streamOut('Finished!\n')
def ft_printHeader(s): l = os.get_terminal_size().columns print(BOLD + BLU + "{:#^{x}}".format("#", x=l)) print("#{:^{x}}#".format(s, x=l - 2)) print("{:#^{x}}".format("#", x=l) + NC)
#!/usr/bin/env python3 import sys from os import (get_terminal_size, path, devnull) from signal import SIGINT from configparser import ConfigParser from abc import ABC, abstractmethod from typing import Tuple from subprocess import Popen, PIPE from time import time, sleep from unittest import (TestLoader, TextTestRunner) from click import (secho, group) EXIT_SUCCESS = 0 EXIT_FAILURE = 1 SEPARATOR = '-' * get_terminal_size().columns TEST_FILENAMES_PATTERN = 'test_*' DEVNULL = open(devnull, 'wb') class ConfigBase(ABC): def __init__(self) -> None: self.path_this = path.dirname(__file__) self.start_time = time() path_ini_file = path.join(self.path_this, 'configure.ini') if not path.exists(path_ini_file): self.echo_error('Could not access {}'.format(path_ini_file)) sys.exit(EXIT_FAILURE) self.configs = ConfigParser() self.configs.read(path_ini_file)
def logging_filter(record: logging.LogRecord) -> bool: console_visible_level = CONSOLE_VERBOSE_LOGGING_LEVEL if Console.is_verbose_logging else CONSOLE_DEFAULT_LOGGING_LEVEL if record.levelno >= console_visible_level: lines = int(len(record.getMessage()) / os.get_terminal_size().columns) + 1 Console.console_line_counter += lines return True
from urllib.request import urlopen, urlparse from bs4 import BeautifulSoup import codecs, lxml, os from modules import helper import win_unicode_console , colorama width = os.get_terminal_size().columns # Windows deserves coloring too :D G = '\033[92m' # green Y = '\033[93m' # yellow B = '\033[94m' # blue R = '\033[91m' # red W = '\33[97m' # white try: pages = set() url = input("%s\t\t\tExample :- %szugtech.com (or) http://zugtech.com/%s\n\n\n[*] Enter the URL >> %s"%(Y,G,W,R)) print('%s_'%(W) * width) def getLinks(pageUrl): global pages clean = helper.clean(url) domain = helper.get_domain(clean) html = urlopen(clean) bsObj = BeautifulSoup(html, "lxml") for link in bsObj.findAll("a"): if 'href' in link.attrs: if link.attrs['href'] not in pages: #We have encountered a new page newPage = link.attrs['href']
#!/usr/bin/python # 20140824 import random import os lista = [] escolha = "S" sorteados = [] n = 1 #print("\n" * 100) #print("\n") #print ('SORTEIO EETAD') print("\n" * os.get_terminal_size().lines) while escolha == "S": if len(lista) > 0: sorteado = (lista[random.randrange(len(lista))]) sorteados.append(sorteado) print("\n" * os.get_terminal_size().lines) print('SORTEIO EETAD:') print("\n") print("O " + str(n) + "º ganhador(a) foi: " + sorteado) n += 1 print("\n" * 20) print("\n") escolha = input("Deseja sortear mais um nome? [S/N]: ") #print("\n" * 130) if escolha == "Sim": escolha = "S" if escolha == "sim": escolha = "S"
def win_dimensions(): return os.get_terminal_size()
i.MakeEnemy() if i.checkmurder(bomber): bomber.SetPosition(2, 2) bomber.MakeBomber() ''' Updatation of objects on the board ''' def movement(): bombs_update() enemy_update() while True: col = os.get_terminal_size().columns line = os.get_terminal_size().lines os.system('tput reset') for i in range(int((line - 10) / 2)): print() for i in Init: print(colored(i.center(col), "yellow", attrs=["bold"])) try: input() except: sys.exit() break ''' Main infinite loop of the board ''' while True:
class bcolors: HEADER = '\033[1;97m' INFO = '\033[1;97m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' try: rows, columns = os.get_terminal_size(0) except OSError: # if running as GitHub Action rows, columns = 24, 80 def print_separator(symbol, text, colour=None): left = int((columns - len(text) - 2) / 2) right = columns - left - len(text) - 2 if colour: print(f"{colour}", end='') print(symbol * left, text, symbol * right) if colour: print(f"{bcolors.ENDC}", end='') def print_line(text, status=None):
import sys from random import randint import requests from pprint import pprint import json import re import os debug = True yellow = "\033[33m" normal = "\033[0;33;0m" grey = "\033[90m" try: columns, rows = os.get_terminal_size(0) except OSError: columns, rows = os.get_terminal_size(1) def help(): print("Sonos") print("sonos cmd [args]") print( "args := (i)nfo, (n)ext, (pr)evious, (pl)ay, (p)ause, (s)huffle, (v)olume [0-100], (q)ueue [index], (r)andom, (r)e(m)ove, playlist/add, (l)yrics [restart?], (s)ee(k)" ) def info(): track = sonos.get_current_track_info() print(
def main(): # LOG Script Start Date/ Time start_time = datetime.datetime.now() master_log.append('\n### START ### : ' + str(start_time) + '\n') # Use OS function to centralise output to Terminal print(bcolors.CWHITETXTREDBG) print('\n' + ('Network Borg Python3 Script Started @ ' + str(start_time)).center(os.get_terminal_size().columns)) print(bcolors.CEND) ''' CLI ARGUMENTS ''' # Command Line Arguement Parser parser = ArgumentParser(description='Usage:') # Parse command line arguements. action='store_true' defines an arguement # without a value. i.e. if -t exisits args.tech == True # Example 1: # 'python3 network_borg[v***].py -y {YAML Group} -t -v' # Defines a YAML Group with the -t (tech-support) and -v (version check) # flags set to true. # # Example 2: # 'python3 network_borg[v***].py -y {YAML Group} -o' # Defines a YAML Host with the -o {override} flag set to true. Will prompt # for username and password even if Environmental Variables are defined. parser.add_argument('-y', '--yaml', type=str, required=True, help='YAML Group or Host') parser.add_argument('-u', '--username', type=str, help='Username [OPTIONAL]') parser.add_argument('-p', '--password', type=str, help='Password [OPTIONAL]') parser.add_argument('-t', '--tech', action='store_true', help='Capture Tech Support [OPTIONAL]') parser.add_argument('-f', '--ftp', action='store_true', help='Upload Tech Support to FTP [OPTIONAL]') parser.add_argument('-c', '--clear', action='store_true', help='Clear Caches (e.g. ARP) [OPTIONAL]') parser.add_argument( '-v', '--version', action='store_true', help= 'Verifies Current OS Version against YAML defined Target OS Version [OPTIONAL]' ) parser.add_argument( '-o', '--override', action='store_true', help='Override Stored Credentials and allow manual input only') parser.add_argument('-d', '--debug', action='store_true', help='Debug Output [OPTIONAL]') parser.add_argument( '-commit', '--commit', action='store_true', help='[OPTIONAL] Commits the final config PUSH, otherwise Report ONLY') cli_args = parser.parse_args() SESSION_TK = args(cli_args) master_log.append('Script Executed By: ' + str(SESSION_TK['ENV_user_un']) + '\n') ''' YAML: Get List of Hosts ''' # Generate host_list from -y YAML command line argument yaml_status, yaml_log, yaml_dict = genyml(SESSION_TK['ARG_yaml']) if SESSION_TK['ARG_debug'] == True: print('\n**DEBUG (network_borg.py) : YAML DICT') print(yaml_dict) # Append all log entries to master_log for line in yaml_log: master_log.append(line) print(bcolors.CWHITETXTBLUDBG) print('\nYAML Host List:\n') for item, object in yaml_dict.items(): print('- ' + item) print(bcolors.CEND) # For yaml_host in YAML Dict, process... for yaml_host in yaml_dict.items(): ''' YAML: Host ''' # yaml_dict will look something like (structured for understanding) # {'ROUTER-N7K-A-01.company.x': # {'NAPALM DRIVER': 'nxos_ssh', # 'LOC': 'Building X, Floor Y, Room Z, CAB A', # 'DOMAIN': 'company.x', # 'ENV': 'Development' # } # } # YAML_fqdn is in the root dictionary [0]. All other values are in the # nested dictionary [1] YAML_TK = {} # Re-initialise YAML_TK for each pass of yaml_host # Add values to the YAML_TK (Token) YAML_TK['YAML_fqdn'] = yaml_host[0] YAML_TK['YAML_driver'] = yaml_host[1]['DRIVER'] # Required by NAPALM YAML_TK['YAML_loc'] = yaml_host[1]['LOC'] YAML_TK['YAML_domain'] = yaml_host[1]['DOMAIN'] YAML_TK['YAML_env'] = yaml_host[1]['ENV'] if SESSION_TK['ARG_debug'] == True: print(bcolors.CWHITETXTCYANBK) print('\n**DEBUG (network_borg.py) : ' + YAML_TK['YAML_fqdn'] + ' Node Information:') print('FQDN: ' + YAML_TK['YAML_fqdn']) print('DRIVER: ' + YAML_TK['YAML_driver']) print('LOC: ' + YAML_TK['YAML_loc']) print('DOMAIN: ' + YAML_TK['YAML_domain']) print('ENVIRO: ' + YAML_TK['YAML_env']) print(bcolors.CEND) else: print(bcolors.CWHITETXTCYANBK) print('\nWorking On ' + YAML_TK['YAML_fqdn'] + '... Please Wait...') print(bcolors.CEND) ''' SYNC ''' sync_status, sync_log = sync(SESSION_TK, YAML_TK) for line in sync_log: master_log.append(line) # LOG Script End Date/ Time end_time = datetime.datetime.now() master_log.append('\n### END ### : ' + str(end_time)) diff_time = end_time - start_time master_log.append('\n### ELAPSED ### : ' + str(diff_time) + '\n') # PRINT master_log print(bcolors.CWHITETXTREDBG) print(bcolors.CBOLD) print(' *** RESULTS *** ') print(bcolors.CEND) for line in master_log: print(line) # WRITE master_log to file # Make a folder in script working directory to store results logdir = '../LOGS/network_borg/' try: os.makedirs(logdir) except FileExistsError: pass # Folder exisits so nothing to do f = open(logdir + str(start_time) + '.log', 'w') for line in master_log: f.write(line + '\n') f.close()
def get_size(): sz = os.get_terminal_size() print(sz) print(sz.columns, sz.lines)
def ret(text, wyp): return text.center(os.get_terminal_size().columns, wyp)
def terminal_size(): """\nIt returns the terminal size\n""" if par.nocolor: return [100, 45] else: return list(_os.get_terminal_size())
def _print_domain(self, msg): console_width = os.get_terminal_size()[0] msg = '\r' + msg + ' ' * (console_width - len(msg)) # msg = '\033[0;31;47m%s{}\033[0m'.format(msg) sys.stdout.write(msg)