Skip to content

Instantly share code, notes, and snippets.

@GreatBahram
Created June 11, 2019 18:37
Show Gist options
  • Save GreatBahram/f3b6992027cb546829ee415b97f045b7 to your computer and use it in GitHub Desktop.
Save GreatBahram/f3b6992027cb546829ee415b97f045b7 to your computer and use it in GitHub Desktop.
How to use subprocess methods in general.
from subprocess import STDOUT, CalledProcessError, check_output
class SomethingYouWant:
def __init__(self, working_dir):
self.working_dir= working_dir
def _build_cmd(self, cmd):
return cmd.split(' ')
def execute(self, cmd, cwd=None, kill_after_timeout=None, with_extended_output=False, shell=False, env=None):
""" Handle executing the command on the shell and return the returned information.
:param cmd:
The cmd argument list to execute.
It should be a string, or a sequence of program arguments. The
program to execute is the first item in the args sequence or string.
:param env:
A dictionary of environment variables to be passed to `subprocess.Popen`.
:param shell:
Whether to invoke commands through a shell (see `Popen(..., shell=True)`).
It overrides :attr:`USE_SHELL` if it is not `None`.
:param kill_after_timeout:
To specify a timeout in seconds for the git command, after which the process
should be killed.
"""
print("Debug cmd: {}".format(cmd))
if cwd is None:
cwd = self.working_dir
inline_env = env
env = os.environ.copy()
env["LANGUAGE"] = "C"
env["LC_ALL"] = "C"
if inline_env is not None:
env.update(inline_env)
if shell is False:
cmd = self._build_cmd(cmd)
status = 0
stdout_value = stderr_value = ''
try:
stdout_value = check_output(
cmd,
cwd=cwd,
env=env,
stderr=STDOUT, # If You want to capture stderr as well.
shell=shell,
encoding='utf-8', # Care should be taken with encoding!
)
except CalledProcessError as e:
stderr_value = e.output
status = e.returncode
print("Debug return:", status, stdout_value, stderr_value)
if with_extended_output:
return (status, stdout_value.strip(), stderr_value.strip())
else:
return status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment