Created
July 17, 2021 08:48
-
-
Save GluTbl/2211ad5691fcb6937a85cea2495e44d3 to your computer and use it in GitHub Desktop.
[Python runnng subprocess]
This file contains hidden or 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
################Executing Command################ | |
def execution_timer(time_out, cmd_process): | |
kill = lambda process: process.kill() | |
my_timer = Timer(time_out, kill, [cmd_process]) | |
try: | |
my_timer.start() | |
stdout, stderr = cmd_process.communicate() | |
finally: | |
my_timer.cancel() | |
try: | |
return stdout, stderr | |
except Exception as e: | |
print(e) | |
return None, None | |
def execute_command(command: str, path=None, time_out=None): | |
logger.info(f"Command: {command}") | |
command_splited = shlex.split(command) | |
if path is None: | |
cmd_process = subprocess.Popen(command_splited) | |
else: | |
cmd_process = subprocess.Popen(command_splited, cwd=path) | |
if time_out is not None: | |
stdout, stderr = execution_timer(time_out, cmd_process) | |
else: | |
stdout, stderr = cmd_process.communicate() | |
return stdout, stderr | |
def execute_command_silently(command: str, path=None, time_out=None): | |
logger.info(f"Command: {command}") | |
command_splited = shlex.split(command) | |
if path is None: | |
cmd_process = subprocess.Popen(command_splited, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE) | |
else: | |
cmd_process = subprocess.Popen(command_splited, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, cwd=path) | |
if time_out is not None: | |
stdout, stderr = execution_timer(time_out, cmd_process) | |
else: | |
stdout, stderr = cmd_process.communicate() | |
return stdout, stderr | |
############################### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment