Skip to content

Instantly share code, notes, and snippets.

@GluTbl
Created July 17, 2021 08:48
Show Gist options
  • Save GluTbl/2211ad5691fcb6937a85cea2495e44d3 to your computer and use it in GitHub Desktop.
Save GluTbl/2211ad5691fcb6937a85cea2495e44d3 to your computer and use it in GitHub Desktop.
[Python runnng subprocess]
################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