From b557a86b37e0f24eb5b4bf54da7f39836251eea6 Mon Sep 17 00:00:00 2001 From: rtmigo Date: Fri, 30 Apr 2021 03:30:55 +0300 Subject: [PATCH] publish --- .gitignore | 1 + bgprocess/constants.py | 2 +- bgprocess/process.py | 38 +++++++++++++++++++------------------- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/.gitignore b/.gitignore index 30c7309..cdda6a8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # Editors +__about__.txt .vscode/ .idea/ diff --git a/bgprocess/constants.py b/bgprocess/constants.py index 68cdeee..6849410 100644 --- a/bgprocess/constants.py +++ b/bgprocess/constants.py @@ -1 +1 @@ -__version__ = "1.0.5" +__version__ = "1.1.0" diff --git a/bgprocess/process.py b/bgprocess/process.py index 784ac10..65d63d4 100644 --- a/bgprocess/process.py +++ b/bgprocess/process.py @@ -7,6 +7,7 @@ import threading import time import unittest +from pathlib import Path from subprocess import Popen from typing import * @@ -19,36 +20,24 @@ class LineWaitingTimeout(Exception): class BackgroundProcess: - # я создал этот класс с конкретной целью: запускать HTTP-сервер в параллельном процессе, тогда как текущий - # процесс запускает юниттесты. - # - # Пример использования: запускаем приложение и читаем строки, пока не встретим какую-то специальную - # - # with BackgroundProcess(["prog", "-arg1", "-arg2"]) as bp: - # for line in bp.iterLines(): - # if something in line: - # break - # - # Важно для понимания принципа: хотя обычно поток это часть процесса, в данном случае, наоборот: - # образно говоря, фоновый процесс Popen работает "внутри" параллельного потока Thread. - # - # Пока процесс не остановлен, работает и поток. Если процесс уже отработал или выкинул ошибку, сначала - # остановится процесс, потом поток. - def __init__(self, args: List[str], term_timeout=1, buffer_output=False, print_output=False, - add_env: Dict[str, str] = None): + add_env: Dict[str, str] = None, + cwd: str = None): self._subproc: Optional[Popen] = None + self.cwd = cwd + self.args = args self.thread = None self._disposed = False - # чтобы закрыть программу, мы будем отправлять ей сигналы: вежливые и не очень. - # После сигнала мы будем ждать столько секунд, что программа отреагирует: + # чтобы закрыть программу, мы будем отправлять ей сигналы: вежливые и + # не очень. После сигнала мы будем ждать столько секунд, что программа + # отреагирует: self.termTimeout: float = term_timeout # self.bufferOutput = self.bufferOutput @@ -68,6 +57,7 @@ def __thread_method(self): stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, + cwd=self.cwd, env=self._env, close_fds=True) @@ -313,6 +303,16 @@ def testWaitLine(self): with BackgroundProcess(["sleep", "3"]) as bp: bp.next_line(lambda s: s == "never!", match_timeout=0.25) + def test_cwd_set(self): + for d in [Path(__file__).parent, + Path(__file__).parent.parent / '.github']: + with BackgroundProcess(["pwd"], cwd=str(d)) as bp: + self.assertEqual(bp.next_line(), str(d)) + + def test_cwd_unset(self): + with BackgroundProcess(["pwd"]) as bp: + self.assertEqual(bp.next_line(), str(Path('.').absolute())) + if __name__ == "__main__": TestBackgroundProcess().testWaitLine()