4 alternatives:
import subprocess # VARIABLE=12 # v_num_final_distinct_grid_disks_per_cell_and_dg = subprocess.check_output("cat /tmp/logall | sort -u | grep -v VARIABLE", shell=True) # grep -v is invert match def insecure(variable: str) -> str: return subprocess.check_output(f"cat /tmp/logall | sort -u | grep -v {variable}", shell=True, encoding="utf8") def silly(variable: str) -> str: """ Using PIPE to connect stdout with stdin of next process """ cat_proc = subprocess.Popen(["cat", "/tmp/logall"], encoding="utf8", stdout=subprocess.PIPE) sort_proc = subprocess.Popen(["sort", "-u"], encoding="utf8", stdin=cat_proc.stdout, stdout=subprocess.PIPE) grep_proc = subprocess.Popen(["grep", "-v", variable], encoding="utf8", stdin=sort_proc.stdout, stdout=subprocess.PIPE) grep_proc.wait() return grep_proc.stdout.read() def better(variable: str) -> str: lines = [] with open("/tmp/logall") as fd: # fd is the the file-object # iterating over fd -> lines # creating a set from fd -> unique lines # sort set -> sorted unique lines for line in sorted(set(fd)): if variable not in line: lines.append(line.rstrip()) return "\n".join(lines) def better2(variable: str) -> list[str]: with open("/tmp/logall") as fd: return [ line.rstrip() for line in sorted(set(fd)) if variable not in line ]
better2
uses a list-comprehension to return all not matching lines as a list. The other functions do return the whole text as a single str
.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!