Skip to content

Instantly share code, notes, and snippets.

@PlugaruT
Created June 3, 2016 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlugaruT/f69d0a5d6247fc014c2d35834655d341 to your computer and use it in GitHub Desktop.
Save PlugaruT/f69d0a5d6247fc014c2d35834655d341 to your computer and use it in GitHub Desktop.
Function for running a given command with, or without pipes.
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