[docs]defset_environment(name:str,value:str,env:dict[str,str]|os._Environ[str]=os.environ)->str:"""Set up the environment variable and print debug message. Parameters ---------- name The name of the environment variable to set value The value to set the environment variable to env Optional environment (dictionary) where to set the variable at Returns ------- The value just set. """env[name]=valuelogger.info(f"environ['{name}'] = '{value}'")returnvalue
[docs]defhuman_time(seconds:int|float,granularity:int=2)->str:"""Return a human readable time string like "1 day, 2 hours". This function will convert the provided time in seconds into weeks, days, hours, minutes and seconds. Parameters ---------- seconds The number of seconds to convert granularity The granularity corresponds to how many elements will output. For a granularity of 2, only the first two non-zero entries are output. Returns ------- A string, that contains the human readable time. """result:list[str|None]=[]forname,countin_INTERVALS:value=seconds//countifvalue:seconds-=value*countifvalue==1:name=name.rstrip("s")result.append(f"{int(value)}{name}")else:# Add a blank if we're in the middle of other valuesiflen(result)>0:result.append(None)ifnotresult:ifseconds<1.0:return"%.2f seconds"%secondsifseconds==1:return"1 second"return"%d seconds"%secondsreturn", ".join([xforxinresult[:granularity]ifxisnotNone])
[docs]defrun_cmdline(cmd:list[str],logger:logging.Logger,**kwargs,)->int:"""Run a command on a environment, logs output and reports status. Parameters ---------- cmd The command to run, with parameters separated on a list of strings logger A logger to log messages to console kwargs Further kwargs to be set on the call to :py:class:`subprocess.Popen`. Returns ------- The exit status of the command. """logger.info("(system) %s"%" ".join(cmd))start=time.time()p=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,bufsize=1,universal_newlines=True,**kwargs,)forlineiniter(p.stdout.readline,""):sys.stdout.write(line)sys.stdout.flush()ifp.wait()!=0:raiseRuntimeError("command `%s' exited with error state (%d)"%(" ".join(cmd),p.returncode))total=time.time()-startlogger.info("command took %s"%human_time(total))returnp.pid
[docs]defuniq(seq:list[typing.Any],idfun:typing.Callable|None=None)->list[typing.Any]:"""Very fast, order preserving uniq function."""# order preservingidfun=idfunor(lambdax:x)seen={}result=[]foriteminseq:marker=idfun(item)# in old Python versions:# if seen.has_key(marker)# but in new ones:ifmarkerinseen:continueseen[marker]=1result.append(item)returnresult