Created
October 22, 2015 08:13
-
-
Save jordiclariana/2d260a65a252d1510933 to your computer and use it in GitHub Desktop.
Python execute comand
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
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