Skip to content

Commit 242a8ae

Browse files
committed
Reduce code duplication
1 parent 92f30e6 commit 242a8ae

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

command_runner/__init__.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
# Don't bother with an ImportError since we need command_runner to work without dependencies
4343
try:
4444
import psutil
45+
4546
# Also make sure we directly import priority classes so we can reuse them
4647
if os_name == "nt":
4748
from psutil import (
@@ -78,7 +79,7 @@
7879
IOPRIO_CLASS_IDLE = 3
7980
IOPRIO_CLASS_BE = 2
8081
IOPRIO_CLASS_RT = 1
81-
82+
8283

8384
# Python 2.7 does not have priorities defined in subprocess module, but psutil has
8485
# Since Windows and Linux use different possible values, let's simplify things by
@@ -308,6 +309,17 @@ def wrapper(*args, **kwargs):
308309
PIPE = subprocess.PIPE
309310

310311

312+
def _check_priority_value(priority):
313+
"""
314+
Check if priority int is valid
315+
"""
316+
if isinstance(priority, int):
317+
if os_name == "nt":
318+
raise ValueError("Priority int not valid on Windows: {}".format(priority))
319+
elif -20 <= priority <= 20:
320+
raise ValueError("Priority not valid on Unix: {}".format(priority))
321+
322+
311323
def _set_priority(
312324
pid, # type: int
313325
priority, # type: Union[int, str]
@@ -320,8 +332,7 @@ def _set_priority(
320332
priority = priority.lower()
321333

322334
if priority_type == "process":
323-
if isinstance(priority, int) and os_name != "nt" and -20 <= priority <= 20:
324-
raise ValueError("Bogus process priority int given: {}".format(priority))
335+
_check_priority_value(priority)
325336
if priority not in ["low", "normal", "high"]:
326337
raise ValueError(
327338
"Bogus {} priority given: {}".format(priority_type, priority)
@@ -1000,10 +1011,8 @@ def _monitor_process(
10001011

10011012
process_prio = 0
10021013
if priority:
1003-
if isinstance(priority, int) and os_name != "nt" and -20 <= priority <= 20:
1004-
raise ValueError("Bogus process priority int given: {}".format(priority))
1005-
else:
1006-
process_prio = PRIORITIES["process"][priority.lower()]
1014+
_check_priority_value(priority)
1015+
process_prio = PRIORITIES["process"][priority.lower()]
10071016
if os_name == "nt" and sys.version_info >= (3, 7):
10081017
kwargs["creationflags"] = kwargs.pop("creationflags", 0) | process_prio
10091018
else:
@@ -1285,4 +1294,4 @@ def deferred_command(command, defer_time=300):
12851294
)
12861295

12871296

1288-
command_runner("ping 127.0.0.1 -n 100", live_output=True, priority="low")
1297+
command_runner("ping 127.0.0.1 -n 100", live_output=True, priority="low")

0 commit comments

Comments
 (0)