Skip to content

Instantly share code, notes, and snippets.

@jordiclariana
Created October 22, 2015 08:13
Show Gist options
  • Save jordiclariana/2d260a65a252d1510933 to your computer and use it in GitHub Desktop.
Save jordiclariana/2d260a65a252d1510933 to your computer and use it in GitHub Desktop.
Python execute comand
import subprocess, shlex
def cmd_execute(command):
cmd = shlex.split(command, posix = False)
try:
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
preturn = p.wait()
stdout = ''
tmp_stdout = p.stdout.readline()
while tmp_stdout:
stdout = stdout + tmp_stdout.decode('UTF-8')
tmp_stdout = p.stdout.readline()
stderr = ''
tmp_stderr = p.stderr.readline()
while tmp_stderr:
stderr = stderr + tmp_stdout.decode('UTF-8')
tmp_stdout = p.stderr.readline()
if preturn != 0:
print("Error executing {command} ({error}):\nSTDERR: {stderr}\nSTDOUT:{stdout}".format(
stderr=stderr, stdout=stdout, command=command, error=preturn))
return [preturn, stdout, stderr]
except Exception as e:
print("Exception on execution:\n{exception}".format(exception=e))
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment