Skip to content
This repository was archived by the owner on Aug 25, 2024. It is now read-only.

Commit 4f9a28a

Browse files
committed
util: os: prepend_to_path
Signed-off-by: John Andersen <[email protected]>
1 parent ea3ba20 commit 4f9a28a

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

dffml/util/os.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import os
2-
from contextlib import contextmanager
2+
import contextlib
33

44

5-
@contextmanager
5+
@contextlib.contextmanager
66
def chdir(new_path):
77
"""
88
Context manager to change directroy
@@ -13,3 +13,17 @@ def chdir(new_path):
1313
yield
1414
finally:
1515
os.chdir(old_path)
16+
17+
18+
@contextlib.contextmanager
19+
def prepend_to_path(*args: str):
20+
"""
21+
Prepend all given directories to the ``PATH`` environment variable.
22+
"""
23+
old_path = os.environ.get("PATH", "")
24+
# TODO Will this work on Windows?
25+
os.environ["PATH"] = ":".join(list(map(str, args)) + old_path.split(":"))
26+
try:
27+
yield
28+
finally:
29+
os.environ["PATH"] = old_path

tests/util/test_os.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import os
2+
import unittest
3+
4+
from dffml.util.os import prepend_to_path
5+
6+
7+
class TestOS(unittest.TestCase):
8+
def test_prepend_to_path(self):
9+
old_path = os.environ["PATH"]
10+
with prepend_to_path("jellybeans", "fritos"):
11+
self.assertEqual(
12+
os.environ["PATH"], "jellybeans:fritos:" + old_path
13+
)

0 commit comments

Comments
 (0)