Python运维实战:子进程调用与文件归档操作详解

Oliver
Oliver
发布时间:2026-10-15 | 5人浏览过
原创

本文介绍如何利用Python的subprocess模块安全调用外部程序,包括处理返回值、超时机制及捕获输出。同时详解shutil模块在文件复制、移动、目录遍历及归档创建中的高级用法,涵盖符号链接处理、忽略模式及错误处理,为运维自动化提供实用代码示例。

Python在运维场景中常能替代Shell脚本。对于单行命令,通常直接使用Shell;而对于复杂的多步操作,则更倾向于使用Python。本文整理并分享几类常用的Python运维脚本技巧。

1. 执行外部程序或命令

假设有一个已编译为.out文件的C语言程序cal.c,其功能是接收两个命令行参数并打印它们的和。我们需要通过Python调用该C程序,并验证其是否正常退出(正常退出时返回码为0)。

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
    int a = atoi(argv[1]);
    int b = atoi(argv[2]);
    int c = a + b;
    printf("%d + %d = %d\n", a, b, c);
    return 0;
}

可以使用subprocess模块中的run函数来启动一个子进程执行该程序。

res = subprocess.run(["Python-Lang/cal.out", "1", "2"])
print(res.returncode) 

执行后,控制台会打印出进程的返回码0,表示程序成功执行。

1 + 2 = 3 0

如果程序陷入死循环或被强制终止,返回码将不同。例如,将while.c编译为.out文件,其内部包含无限循环。

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
    while(1);
    return 0;
}

同样使用run函数获取其返回码。

res = subprocess.run("Python-Lang/while.out")
print(res.returncode)

若在程序运行期间通过Shell命令强制终止它,例如使用kill命令。

(base) orion-orion@MacBook-Pro Python-Lang % ps -a |grep while 11829 ttys001 0:17.49 Python-Lang/while.out 11891 ttys005 0:00.00 grep while (base) orion-orion@MacBook-Pro Python-Lang % kill 11829

此时控制台打印的进程返回值为-15。负值-N表示子进程被信号N终止,而kill命令默认发送的信号是15(SIGTERM),该信号会导致进程终止。

-15

如果程序陷入死循环且无法正常退出,不能无限期等待。此时可以设置超时机制并捕获异常。

try:
    res = subprocess.run(["Python-Lang/while.out"], capture_output=True, timeout=5)
except subprocess.TimeoutExpired as e:
    print(e)

当超过设定时间时,会打印出超时异常信息。

Command '['Python-Lang/while.out']' timed out after 5 seconds

有时需要获取程序的输出结果,此时可以添加capture_output参数,然后访问返回对象的stdout属性即可。

res = subprocess.run(["netstat", "-a"], capture_output=True)
out_bytes = res.stdout

输出结果以字节串形式返回,如需以文本形式解读,可进一步进行解码操作。

out_text = out_bytes.decode("utf-8")
print(out_text)

解码后即可正常获取文本形式的输出结果。

... kctl 0 0 33 6 com.apple.netsrc kctl 0 0 34 6 com.apple.netsrc kctl 0 0 1 7 com.apple.network.statistics kctl 0 0 2 7 com.apple.network.statistics kctl 0 0 3 7 com.apple.network.statistics (base) orion-orion@MacBook-Pro Learn-Python %

一般情况下,命令执行无需依赖底层Shell(如sh、bash等),提供的字符串列表会直接传递给系统调用,例如os.execve()。若希望命令通过Shell执行,只需指定参数shell=True,并将命令以字符串形式传入。例如,执行涉及管道、I/O重定向等复杂Shell命令时,可如此编写:

out_bytes = subprocess.run("ps -a|wc -l> out", shell=True)

2. 文件和目录操作(命名、删除、拷贝、移动等)

在处理文件名和路径时,为保证最佳的可移植性(特别是在Unix和Windows系统间切换),建议使用os.path模块中的函数。例如:

import os
file_name = "/Users/orion-orion/Documents/LocalCode/Learn-Python/Python-Lang/test.txt"
print(os.path.basename(file_name)) 
# test.txt
print(os.path.dirname(file_name))
# /Users/orion-orion/Documents/LocalCode/Learn-Python/Python-Lang
print(os.path.split(file_name))
# ('/Users/orion-orion/Documents/LocalCode/Learn-Python/Python-Lang', 'test.txt')
print(os.path.join("/new/dir", os.path.basename(file_name)))
# /new/dir/test.txt
print(os.path.expanduser("~/Documents"))
# /Users/orion-orion/Documents

其中os.path.expanduser在用户或$HOME环境变量未知时,将不做任何操作。如本例中$HOME的值为/Users/orion-orion:

(base) orion-orion@MacBook-Pro ~ % echo $HOME
/Users/orion-orion

若要删除文件,请使用os.remove(删除前建议先判断文件是否存在):

file_name = "Python-Lang/test.txt"
if os.path.exists(file_name):
    os.remove(file_name)

接下来介绍如何拷贝文件。最直接的方法是调用Shell命令:

os.system("cp Python-Lang/test.txt Python-Lang/test2.txt")

这种方式不够优雅。若不通过Shell命令实现,可使用shutil模块,该模块提供了一系列对文件和文件集合的高阶操作,包括文件拷贝和移动/重命名。这些函数的参数均为字符串,用于指定文件或目录名称。示例如下:

src = "Python-Lang/test.txt"
dst = "Python-Lang/test2.txt"

# 对应cp src dst (拷贝文件,存在则覆盖)
shutil.copy(src, dst) 


src = "Python-Lang/sub_dir"
dst = "Python-Lang/sub_dir2"
# 对应cp -R src dst (拷贝整个目录树)
shutil.copytree(src, dst)

src = "Python-Lang/test.txt"
dst = "Python-Lang/sub_dir/test2.txt"
# 对应mv src dst (移动文件,可选择是否重命名)
shutil.move(src, dst)

如注释所示,这些函数的语义与Unix命令类似。若对Unix下的文件拷贝/移动等操作不熟悉,可参考Linux shell进行文件解压,复制和移动详解。

默认情况下,若源文件是符号链接,目标文件将是该链接指向文件的拷贝。若仅需拷贝符号链接本身,可提供关键字参数follow_symlinks:

shutil.copy(src, dst, follow_symlinks=True)

若希望在拷贝目录时保留符号链接,可采取以下做法:

shutil.copytree(src, dst, symlinks=True)

有时在拷贝整个目录时需忽略特定文件或目录,例如.pyc这类中间过程字节码。可为copytree提供一个ignore函数,该函数以目录名和文件名为输入参数,返回需忽略的名称列表(此处用到字符串对象的.endswith方法,用于获取文件类型后缀):

def ignore_pyc_files(dirname, filenames):
    return [name for name in filenames if name.endswith('pyc')] 


shutil.copytree(src, dst, ignore=ignore_pyc_files)

由于忽略文件名模式非常常见,Python已提供一个实用函数ignore_patterns()供直接使用(相关模式使用方法类似.gitignore):

shutil.copytree(src, dst, ignore=shutil.ignore_patterns("*~", "*.pyc"))

注:此处的"*~"模式匹配是文本编辑器(如Vi)产生的以"~"结尾的中间文件。

忽略文件名还常用于os.listdir()中。例如在数据密集型(如机器学习)应用中,需遍历data目录下的所有数据集文件并加载,但需排除.开头的隐藏文件(如.git),否则可能出错,此时可采用下列写法:

import os
import os
filenames = [filename for filename in os.listdir("Python-Lang/data") if not filename.startswith(".")] #注意,os.listdir返回的是不带路径的文件名

回到copytree()。使用copytree()拷贝目录时,一个棘手的问题是错误处理。例如在拷贝过程中遇到损坏的符号链接,或因权限问题导致部分文件无法访问等。对于这种情况,所有遇到的异常会收集到一个列表中,并归组为一个单独的异常,在操作结束时抛出。示例如下:

import shutil

src = "Python-Lang/sub_dir"
dst = "Python-Lang/sub_dir2"

try:
    shutil.copytree(src, dst)
except shutil.Error as e:
    for src, dst, msg in e.args[0]:
        print(src, dst, msg)

若提供了ignore_dangling_symlinks=True,那么copytree将会忽略悬垂的符号链接。

更多关于shutil的使用(如记录日志、文件权限等)可参见shutil文档[4]。

接下来介绍如何使用os.walk()函数遍历层级目录以搜索文件。只需将顶层目录提供给它即可。例如以下函数用于查找特定文件名,并打印所有匹配结果的绝对路径:

import os
def findfile(start, name):
    for relpath, dirs, files in os.walk(start):
        if name in files:
            # print(relpath)
            full_path = os.path.abspath(os.path.join(relpath, name))
            print(full_path)

start = "."
name = "test.txt"
findfile(start, name)

可以看到,os.walk可协助我们遍历目录层级,且对于进入的每个目录层级,它都返回一个三元组,包含:正在检视的目录的相对路径(相对脚本执行路径),正在检视的目录中包含的所有目录名列表,正在检视的目录中包含的所有文件名列表。这里的os.path.abspath接受一个可能是相对的路径并将其组成绝对路径的形式。

我们还可以扩展脚本以完成更复杂的功能,如下面这个函数可打印出所有最近有修改过的文件:

import os
import time
def modified_within(start, seconds):
    now = time.time()
    for relpath, dirs, files in os.walk(start):
        for name in files:
            full_path = os.path.join(relpath, name)
            mtime = os.path.getmtime(full_path)
            if mtime > (now - seconds):
                print(full_path)

start = "."
seconds = 60
modified_within(start, 60)

3. 创建和解包归档文件

如果仅需创建或解包归档文件,可直接使用shutil模块中的高层函数:

import shutil
shutil.make_archive(base_name="data", format="zip", root_dir="Python-Lang/data")
shutil.unpack_archive("data.zip")

其中第二个参数format为期望输出的格式。要获取所支持的归档格式列表,可使用get_archive_formats()函数:

print(shutil.get_archive_formats())
# [('bztar', "bzip2'ed tar-file"), ('gztar', "gzip'ed tar-file"), ('tar', 'uncompressed tar file'), ('xztar', "xz'ed tar-file"), ('zip', 'ZIP file')]

Python也提供了诸如tarfile、zipfile、gzip等模块来处理归档格式的底层细节。例如,若要创建并解包.zip归档文件,可这样编写:

import zipfile

with zipfile.ZipFile('Python-Lang/data.zip', 'w') as zout:
    zout.write(filename='Python-Lang/data/test1.txt', arcname="test1.txt")
    zout.write(filename='Python-Lang/data/test2.txt', arcname="test2.txt")
with zipfile.ZipFile('Python-Lang/data.zip', 'r') as zin:
    zin.extractall('Python-Lang/data2') #没有则自动创建data2目录

参考

[1] https://docs.python.org/3/library/subprocess.html

[2] https://stackoverflow.com/questions/28708531/what-does-do-in-a-gitignore-file

[3] https://stackoverflow.com/questions/7099290/how-to-ignore-hidden-files-using-os-listdir

[4] https://docs.python.org/3/library/shutil.html

到此这篇关于利用Python编写的实用运维脚本分享的文章就介绍到这了,更多相关Python运维脚本内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表