在python中嵌入bash

Ope*_*way 18 python bash interop language-interoperability

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

谢谢

Ian*_*ing 29

理想的方法:

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 Code Online (Sandbox Code Playgroud)

你也可以添加一个很好的__str__方法ScriptException(你肯定需要它来调试你的脚本) - 但我把它留给读者.

如果您不使用stdout=subprocess.PIPEetc,则脚本将直接附加到控制台.如果您有来自ssh的密码提示,这非常方便.因此,您可能希望添加标志来控制是否要捕获stdout,stderr和stdin.

  • 我很确定这比他想要的酷十倍。 (2认同)

gho*_*g74 12

如果要调用系统命令,请使用子进程模块.

  • 最后资源的+1非常有用,并且正确回答了这个问题.这是一个直接链接:http://docs.python.org/library/subprocess.html (6认同)
  • -1使用tinyurl链接到谷歌搜索而不是指向直接有用的资源. (4认同)
  • @Donal,我这样做的原因是因为还有其他有用的站点也显示了子流程示例。此外,第一个搜索结果是文档本身。那根本不是问题。 (2认同)

waf*_*man 5

假设主机系统支持该命令:

import os
os.system('command')
Run Code Online (Sandbox Code Playgroud)

如果你有一个很长的命令,或者一组命令。你可以使用变量。例如:

# this simple line will capture column five of file.log
# and then removed blanklines, and gives output in filtered_content.txt.

import os

filter = "cat file.log | awk '{print $5}'| sed '/^$/d' > filtered_content.txt"

os.system(filter)
Run Code Online (Sandbox Code Playgroud)


Unr*_*son 5

import os
os.system ("bash -c 'echo $0'")
Run Code Online (Sandbox Code Playgroud)

要为你做这件事吗?

编辑:关于可读性

是的,当然,你可以让它更具可读性

import os
script = """
echo $0
ls -l
echo done
"""
os.system("bash -c '%s'" % script)
Run Code Online (Sandbox Code Playgroud)

编辑2:关于宏,没有python到目前为止我不知道,但介于两者之间

import os
def sh(script):
    os.system("bash -c '%s'" % script)

sh("echo $0")
sh("ls -l")
sh("echo done")
Run Code Online (Sandbox Code Playgroud)

和前面的例子一样,你基本上得到你想要的东西(但你必须允许一些辩证的限制)