Created
June 3, 2016 18:02
-
-
Save PlugaruT/f69d0a5d6247fc014c2d35834655d341 to your computer and use it in GitHub Desktop.
Function for running a given command with, or without pipes.
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
from subprocess import Popen | |
from subprocess import PIPE | |
# def run(command): | |
# '''Run the given command and return its output | |
# and exit_code''' | |
# setting parameter shell=True does the same thing, but, security matters | |
# process = Popen(command.split(), stdout=PIPE, shell=True) | |
# (output, _status) = process.communicate() | |
# exit_code = process.wait() | |
# return output, exit_code | |
def run(command): | |
'''Run the given command and return its output | |
and exit_code''' | |
# for some reason there is a problem if there are double or single quotes in command | |
command = command.replace('"', '') | |
command = command.replace("'", "") | |
if "|" in command: | |
command_parts = command.split("|") | |
else: | |
command_parts = [] | |
command_parts.append(command) | |
i = 0 | |
pipe = {} | |
for command_part in command_parts: | |
if i == 0: | |
pipe[i] = Popen(command_part.split(), stdout=PIPE) | |
else: | |
pipe[i] = Popen(command_part.split(), stdin=pipe[i-1].stdout, stdout=PIPE) | |
i = i + 1 | |
(output, _status) = pipe[i-1].communicate() | |
exit_code = pipe[i-1].wait() | |
return output, exit_code | |
# com = 'ls' | |
# com = 'ls -a' | |
# com = 'fortune | cowsay' | |
com = 'ls /dev | grep "ttyS2" | grep "ttyS20"' | |
# com = "ls /dev | grep 'ttyS2' | grep 'ttyS20'" | |
print run(com)[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment