Skip to content

Commit 75552e8

Browse files
committed
process: enable stream_command to filter by pattern
1 parent 7bc5ba7 commit 75552e8

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/warnet/process.py

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
1+
import re
12
import subprocess
23

3-
44
def run_command(command: str) -> str:
55
result = subprocess.run(command, shell=True, capture_output=True, text=True, executable="bash")
66
if result.returncode != 0:
77
raise Exception(result.stderr)
88
return result.stdout
99

1010

11-
def stream_command(command: str) -> bool:
11+
def stream_command(command: str, grep_pattern: str = "") -> bool:
12+
"""Stream output and apply an optional pattern filter."""
1213
process = subprocess.Popen(
1314
["bash", "-c", command],
1415
stdout=subprocess.PIPE,
@@ -18,10 +19,15 @@ def stream_command(command: str) -> bool:
1819
universal_newlines=True,
1920
)
2021

21-
message = ""
22+
pattern = re.compile(grep_pattern) if grep_pattern else None
23+
24+
# Only display lines matching the pattern if grep is specified
2225
for line in iter(process.stdout.readline, ""):
23-
message += line
24-
print(line, end="")
26+
if pattern:
27+
if pattern.search(line):
28+
print(line, end="")
29+
else:
30+
print(line, end="")
2531

2632
process.stdout.close()
2733
return_code = process.wait()

0 commit comments

Comments
 (0)