在Python中嵌入bash
我正在写一个Python脚本,但时间不够了。我需要做一些我在bash中很熟悉的事情,所以我想知道怎么把一些bash命令放进Python脚本里。
谢谢!
9 个回答
7
假设这个命令是你的系统支持的:
import os
os.system('command')
如果你有一个很长的命令,或者一组命令,你可以使用变量来简化它们。比如:
# 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)
34
理想的做法是:
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 连接时,非常方便。所以你可能想添加一些选项,来控制是否捕获标准输出(stdout)、标准错误(stderr)和标准输入(stdin)。
15
如果你想要执行系统命令,可以使用 subprocess 这个模块。