teepopen fix

This commit is contained in:
Max Kainov 2024-08-10 10:01:16 +02:00
parent 427016a450
commit 8e35b082b2

View File

@ -3,7 +3,6 @@
import logging
import os
import signal
import subprocess
import sys
from io import TextIOWrapper
from pathlib import Path
@ -34,7 +33,6 @@ class TeePopen:
self.timeout_exceeded = False
self.terminated_by_sigterm = False
self.terminated_by_sigkill = False
self.pid = 0
def _check_timeout(self) -> None:
if self.timeout is None:
@ -75,8 +73,7 @@ class TeePopen:
errors="backslashreplace",
)
sleep(1)
self.pid = self._get_child_pid()
print(f"Subprocess started, pid [{self.process.pid}], child pid [{self.pid}]")
print(f"Subprocess started, pid [{self.process.pid}]")
if self.timeout is not None and self.timeout > 0:
t = Thread(target=self._check_timeout)
t.daemon = True # does not block the program from exit
@ -97,22 +94,6 @@ class TeePopen:
self.log_file.close()
def _get_child_pid(self):
# linux only
ps_command = f"ps --ppid {self.process.pid} -o pid="
res = "NA"
try:
result = subprocess.run(
ps_command, shell=True, capture_output=True, text=True
)
res = result.stdout.strip()
pid = int(res)
return pid
except Exception as e:
print(f"Failed to get child's pid, command [{ps_command}], result [{res}]")
print(f"ERROR: getting Python subprocess PID: {e}")
return self.process.pid
def wait(self) -> int:
if self.process.stdout is not None:
for line in self.process.stdout:
@ -125,10 +106,7 @@ class TeePopen:
return self.process.poll()
def send_signal(self, signal_num):
if self.pid:
os.kill(self.pid, signal_num)
else:
print("ERROR: no process to send signal")
os.killpg(self.process.pid, signal_num)
@property
def process(self) -> Popen: