Created
September 12, 2022 11:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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