Skip to content

Instantly share code, notes, and snippets.

@duclos-cavalcanti
Created September 12, 2022 11:00
Show Gist options
  • Save duclos-cavalcanti/3db8b4ead864c2f81f9e10f6cca245fc to your computer and use it in GitHub Desktop.
Save duclos-cavalcanti/3db8b4ead864c2f81f9e10f6cca245fc to your computer and use it in GitHub Desktop.
Search through the output of a command for a specific regex pattern in Python
import subprocess
import os
import re
def search(string:str, pattern:str) -> bool:
x = re.search(pattern, string)
if x:
return True
return False
def run(command:str) -> str:
p = subprocess.run(command.split(),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
output = p.stdout.decode()
return output
patt = "Documents"
out = run(f"ls {os.environ['HOME']}")
print("OUTPUT")
print("------")
print(out)
print(f"SEARCH RESULT: {patt}")
print("-------------")
print(search(out, patt))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment