python中写shell,亲测可用,转自stackoverflow

def run_script(script, stdin=None):
"""Returns (stdout, stderr), raises error on non-zero return code"""
import subprocess
# Note: by using a list here (['bash', ...]) you avoid quoting issues, as the
# arguments are passed in exactly this order (spaces, quotes, and newlines won't
# cause problems):
proc = subprocess.Popen(['bash', '-c', script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode:
raise ScriptException(proc.returncode, stdout, stderr, script)
return stdout, stderr

class ScriptException(Exception):
def init(self, returncode, stdout, stderr, script):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
Exception.init('Error in script')

run_script("shell script")

相关文章:

  • 2022-12-23
  • 2021-10-19
  • 2021-08-09
  • 2022-01-01
  • 2022-12-23
  • 2022-02-04
  • 2022-12-23
  • 2021-11-12
猜你喜欢
  • 2022-02-13
  • 2022-12-23
  • 2021-09-22
  • 2021-12-14
  • 2022-12-23
  • 2021-12-21
相关资源
相似解决方案