May 2025
Intermediate to advanced
506 pages
6h 56m
Chinese
Content preview from 用于 DevOps 的 Python
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,







O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
第 3 章 使用命令行 使用命令行
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
命令行是最重要的工具。虽然有许多功能强大的图形界面工具,但命令行仍然是 DevOps 工作的主阵地。在 Python 中与 shell 环境交互和创建 Python 命令行工具都是在 DevOps 中使用 Python 时所必需的。
使用外壳
Python 提供了与系统和 shell 交互的工具。您应该熟悉sys 、os 和subprocess 模块,因为它们都是必不可少的工具。
使用 sys 模块与译员对话
sys 模块提供了对与 Python 解释器密切相关的变量和方法的访问。
备注
在读取过程中,有两种主要的字节解释方法。第一种是little endian,将随后的每个字节解释为具有更高的重要性(代表更大的数字)。另一种是big endian,假定第一个字节的意义最大,然后依次向下。
您可以使用sys.byteorder 属性查看当前架构的字节顺序:
In[1]:importsysIn[2]:sys.byteorderOut[2]:'little'
您可以使用sys.getsizeof 查看 Python 对象的大小。如果内存有限,这将非常有用:
In[3]:sys.getsizeof(1)Out[3]:28
如果要根据底层操作系统执行不同的行为,可以使用sys.platform 进行检查:
In[5]:sys.platformOut[5]:'darwin'
更常见的情况是,您想使用仅在特定 Python 版本中可用的语言特性或模块。您可以使用sys.version_info 根据运行的 Python 解释器来控制行为。在这里,我们为 Python 3.7、低于 3.7 的 Python 版本 3 和低于 3 的 Python 版本打印不同的信息:
ifsys.version_info.major<3:("You need to update your Python version")elifsys.version_info.minor<7:("You are not running the latest version of Python")else:("All is good.")
在本章后面编写命令行工具时,我们将介绍更多sys 的用法。
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access