I am writting a Python script and I am running out of time. I need to do some things that I know pretty well in bash, so I just wonder how can I embed some bash lines into a
@Ian Bicking's answer is useful but it if only allow us to run scripts. Instead we can come up with a more flexible code where we can run command as well. I have a different approach from his.
#!/usr/bin/env python3
from subprocess import Popen, PIPE
class BashCommandsException(Exception):
def __init__(self, returncode, output, error_msg):
self.returncode = returncode
self.output = output
self.error_msg = error_msg
Exception.__init__('Error in executed command')
def popen_communicate(cmd, stdout_file=None):
"""Acts similir to lib.run(cmd) but also returns the output message captures on
during the run stdout_file is not None in case of nohup process writes its
results into a file
"""
cmd = list(map(str, cmd)) # all items should be string
if stdout_file is None:
p = Popen(cmd, stdout=PIPE, stderr=PIPE)
else:
with open(stdout_file, "w") as outfile:
# output written into file, error will be returned
p = Popen(cmd, stdout=outfile, stderr=PIPE, universal_newlines=True)
output, error = p.communicate()
p.wait()
return p, output, error
output, error = p.communicate()
output = output.strip().decode("utf-8")
error = error.decode("utf-8")
return p, output, error
def run(cmd):
log_file = "/tmp/log.txt"
# if log_file is not provided returned output will be stored in output
p, output, error_msg = popen_communicate(cmd, log_file)
if p.returncode != 0:
raise BashCommandsException(p.returncode, output, error_msg, str(cmd))
return output
if __name__ == "__main__":
# This could be any command you want to execute as you were in bash
cmd = ["bash", "script_to_run.sh"]
try:
run(cmd)
except Exception as e:
print(e)