@Ian Bicking 的回答很有用,但它只允许我们运行脚本。相反,我们可以提出一个更灵活的代码,我们也可以在其中运行命令。我和他的方法不同。
#!/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)