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 logging
import os import os
import signal import signal
import subprocess
import sys import sys
from io import TextIOWrapper from io import TextIOWrapper
from pathlib import Path from pathlib import Path
@ -34,7 +33,6 @@ class TeePopen:
self.timeout_exceeded = False self.timeout_exceeded = False
self.terminated_by_sigterm = False self.terminated_by_sigterm = False
self.terminated_by_sigkill = False self.terminated_by_sigkill = False
self.pid = 0
def _check_timeout(self) -> None: def _check_timeout(self) -> None:
if self.timeout is None: if self.timeout is None:
@ -75,8 +73,7 @@ class TeePopen:
errors="backslashreplace", errors="backslashreplace",
) )
sleep(1) sleep(1)
self.pid = self._get_child_pid() print(f"Subprocess started, pid [{self.process.pid}]")
print(f"Subprocess started, pid [{self.process.pid}], child pid [{self.pid}]")
if self.timeout is not None and self.timeout > 0: if self.timeout is not None and self.timeout > 0:
t = Thread(target=self._check_timeout) t = Thread(target=self._check_timeout)
t.daemon = True # does not block the program from exit t.daemon = True # does not block the program from exit
@ -97,22 +94,6 @@ class TeePopen:
self.log_file.close() 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: def wait(self) -> int:
if self.process.stdout is not None: if self.process.stdout is not None:
for line in self.process.stdout: for line in self.process.stdout:
@ -125,10 +106,7 @@ class TeePopen:
return self.process.poll() return self.process.poll()
def send_signal(self, signal_num): def send_signal(self, signal_num):
if self.pid: os.killpg(self.process.pid, signal_num)
os.kill(self.pid, signal_num)
else:
print("ERROR: no process to send signal")
@property @property
def process(self) -> Popen: def process(self) -> Popen: