This repository has been archived by the owner on Dec 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Started in on unittests for command line utilities
- Loading branch information
Showing
4 changed files
with
110 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
#! /usr/bin/env python | ||
import six | ||
import threading | ||
import subprocess | ||
import traceback | ||
import shlex | ||
|
||
|
||
class Command(object): | ||
""" | ||
Enables to run subprocess commands in a different thread with TIMEOUT option. | ||
Based on jcollado's solution: | ||
http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933 | ||
""" | ||
command = None | ||
process = None | ||
status = None | ||
output, error = '', '' | ||
|
||
def __init__(self, command): | ||
if isinstance(command, six.string_types): | ||
command = shlex.split(command) | ||
self.command = command | ||
|
||
def run(self, timeout=None, **kwargs): | ||
""" Run a command then return: (status, output, error). """ | ||
def target(**kwargs): | ||
try: | ||
self.process = subprocess.Popen(self.command, **kwargs) | ||
self.output, self.error = self.process.communicate() | ||
self.status = self.process.returncode | ||
except: | ||
self.error = traceback.format_exc() | ||
self.status = -1 | ||
# default stdout and stderr | ||
if 'stdout' not in kwargs: | ||
kwargs['stdout'] = subprocess.PIPE | ||
if 'stderr' not in kwargs: | ||
kwargs['stderr'] = subprocess.PIPE | ||
# thread | ||
thread = threading.Thread(target=target, kwargs=kwargs) | ||
thread.start() | ||
thread.join(timeout) | ||
if thread.is_alive(): | ||
self.process.terminate() | ||
thread.join() | ||
return self.status, self.output, self.error |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters