
正文
python中写shell(转)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
python中写shell,亲测可用,转自stackoverflow
To run a bash script, copy from 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")






![【电子书】[职业技术] 《Linux命令行与shell脚本编程大全(第3版)》[Richard Blum][epub+mobi+azw3] 【电子书】[职业技术] 《Linux命令行与shell脚本编程大全(第3版)》[Richard Blum][epub+mobi+azw3]](https://www.04ip.com/template/qe/style/noimg/18.jpg)
