gpt4 book ai didi

python - 在python中嵌入bash

转载 作者:IT老高 更新时间:2023-10-28 21:05:53 25 4
gpt4 key购买 nike

我正在编写 Python 脚本,但时间不多了。我需要在 bash 中做一些我非常熟悉的事情,所以我只是想知道如何将一些 bash 行嵌入到 Python 脚本中。

谢谢

最佳答案

理想的方法:

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')

您还可以为 ScriptException 添加一个不错的 __str__ 方法(您肯定需要它来调试您的脚本)——但我把它留给读者。

如果不使用 stdout=subprocess.PIPE 等,脚本将直接附加到控制台。例如,如果您有来自 ssh 的密码提示,这将非常方便。因此,您可能需要添加标志来控制是否要捕获标准输出、标准错误和标准输入。

关于python - 在python中嵌入bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2651874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com