Python编写运维进程文件目录操作实用脚本示例
本文详解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命令将其终止:
(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下的文件拷贝/移动等操作,可以参考
https://www.jb51.net/article/231477.htm
https://www.jb51.net/article/183084.htm
默认情况下,如果源文件是符号链接,目标文件将是该链接指向文件的拷贝。若只想拷贝符号链接本身,可以提供关键字参数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)
由于忽略文件名这种模式非常常见,已经有一个实用函数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
- [5] Martelli A, Ravenscroft A, Ascher D. Python cookbook[M]. " O'Reilly Media, Inc.", 2015.
以上就是Python编写实用运维进程文件目录操作脚本示例的详细内容,更多关于python运维操作脚本的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













