1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+ """
4+ 01_os_sys_modules.py - os和sys模块的使用
5+
6+ 本文件演示Python标准库中os和sys模块的常用功能:
7+ - os模块:操作系统接口,文件和目录操作
8+ - sys模块:系统相关的参数和函数
9+
10+ 学习目标:
11+ 1. 掌握os模块的基本用法
12+ 2. 理解sys模块的核心功能
13+ 3. 学会处理路径和环境变量
14+ 4. 了解系统信息获取方法
15+ """
16+
17+ import os
18+ import sys
19+ import platform
20+ from pathlib import Path
21+
22+
23+ def demonstrate_os_module ():
24+ """演示os模块的基本功能"""
25+ print ("=" * 50 )
26+ print ("OS模块功能演示" )
27+ print ("=" * 50 )
28+
29+ # 1. 获取当前工作目录
30+ current_dir = os .getcwd ()
31+ print (f"当前工作目录: { current_dir } " )
32+
33+ # 2. 列出目录内容
34+ print (f"\n 当前目录内容:" )
35+ try :
36+ files = os .listdir ('.' )
37+ for i , file in enumerate (files [:5 ], 1 ): # 只显示前5个文件
38+ print (f" { i } . { file } " )
39+ if len (files ) > 5 :
40+ print (f" ... 还有 { len (files ) - 5 } 个文件" )
41+ except PermissionError :
42+ print (" 权限不足,无法列出目录内容" )
43+
44+ # 3. 环境变量操作
45+ print (f"\n 环境变量示例:" )
46+ print (f"PATH变量长度: { len (os .environ .get ('PATH' , '' ))} 字符" )
47+ print (f"HOME目录: { os .environ .get ('HOME' , '未设置' )} " )
48+ print (f"用户名: { os .environ .get ('USER' , os .environ .get ('USERNAME' , '未知' ))} " )
49+
50+ # 4. 路径操作
51+ print (f"\n 路径操作示例:" )
52+ sample_path = "/home/user/documents/file.txt"
53+ print (f"示例路径: { sample_path } " )
54+ print (f"目录名: { os .path .dirname (sample_path )} " )
55+ print (f"文件名: { os .path .basename (sample_path )} " )
56+ print (f"文件名(无扩展名): { os .path .splitext (sample_path )[0 ]} " )
57+ print (f"扩展名: { os .path .splitext (sample_path )[1 ]} " )
58+
59+ # 5. 路径拼接
60+ joined_path = os .path .join ("home" , "user" , "documents" , "file.txt" )
61+ print (f"路径拼接结果: { joined_path } " )
62+
63+ # 6. 文件和目录检查
64+ print (f"\n 文件系统检查:" )
65+ print (f"当前目录是否存在: { os .path .exists ('.' )} " )
66+ print (f"当前目录是否为目录: { os .path .isdir ('.' )} " )
67+ print (f"README.md是否存在: { os .path .exists ('README.md' )} " )
68+ if os .path .exists ('README.md' ):
69+ print (f"README.md是否为文件: { os .path .isfile ('README.md' )} " )
70+ stat_info = os .stat ('README.md' )
71+ print (f"README.md文件大小: { stat_info .st_size } 字节" )
72+
73+
74+ def demonstrate_sys_module ():
75+ """演示sys模块的基本功能"""
76+ print ("\n " + "=" * 50 )
77+ print ("SYS模块功能演示" )
78+ print ("=" * 50 )
79+
80+ # 1. Python版本信息
81+ print (f"Python版本: { sys .version } " )
82+ print (f"Python版本信息: { sys .version_info } " )
83+ print (f"Python可执行文件路径: { sys .executable } " )
84+
85+ # 2. 平台信息
86+ print (f"\n 平台信息:" )
87+ print (f"操作系统: { sys .platform } " )
88+ print (f"字节序: { sys .byteorder } " )
89+ print (f"默认编码: { sys .getdefaultencoding ()} " )
90+
91+ # 3. 模块搜索路径
92+ print (f"\n 模块搜索路径 (前5个):" )
93+ for i , path in enumerate (sys .path [:5 ], 1 ):
94+ print (f" { i } . { path } " )
95+ if len (sys .path ) > 5 :
96+ print (f" ... 还有 { len (sys .path ) - 5 } 个路径" )
97+
98+ # 4. 命令行参数
99+ print (f"\n 命令行参数:" )
100+ print (f"脚本名称: { sys .argv [0 ] if sys .argv else '无' } " )
101+ print (f"参数个数: { len (sys .argv )} " )
102+ if len (sys .argv ) > 1 :
103+ print (f"其他参数: { sys .argv [1 :]} " )
104+ else :
105+ print ("没有额外的命令行参数" )
106+
107+ # 5. 内存和性能信息
108+ print (f"\n 系统信息:" )
109+ print (f"最大整数值: { sys .maxsize } " )
110+ print (f"递归限制: { sys .getrecursionlimit ()} " )
111+
112+ # 6. 标准输入输出
113+ print (f"\n 标准流信息:" )
114+ print (f"标准输入: { sys .stdin .name } " )
115+ print (f"标准输出: { sys .stdout .name } " )
116+ print (f"标准错误: { sys .stderr .name } " )
117+
118+
119+ def demonstrate_platform_info ():
120+ """演示平台相关信息获取"""
121+ print ("\n " + "=" * 50 )
122+ print ("平台信息详细演示" )
123+ print ("=" * 50 )
124+
125+ print (f"系统名称: { platform .system ()} " )
126+ print (f"系统版本: { platform .release ()} " )
127+ print (f"系统详细版本: { platform .version ()} " )
128+ print (f"机器类型: { platform .machine ()} " )
129+ print (f"处理器信息: { platform .processor ()} " )
130+ print (f"架构信息: { platform .architecture ()} " )
131+ print (f"完整平台信息: { platform .platform ()} " )
132+
133+ # 网络主机名
134+ print (f"主机名: { platform .node ()} " )
135+
136+ # Python实现信息
137+ print (f"\n Python实现信息:" )
138+ print (f"Python实现: { platform .python_implementation ()} " )
139+ print (f"Python版本: { platform .python_version ()} " )
140+ print (f"Python编译器: { platform .python_compiler ()} " )
141+
142+
143+ def demonstrate_environment_operations ():
144+ """演示环境变量操作"""
145+ print ("\n " + "=" * 50 )
146+ print ("环境变量操作演示" )
147+ print ("=" * 50 )
148+
149+ # 1. 设置和获取环境变量
150+ test_var = "PYTHON_DEMO_VAR"
151+ test_value = "Hello, Python Standard Library!"
152+
153+ print (f"设置环境变量: { test_var } = { test_value } " )
154+ os .environ [test_var ] = test_value
155+
156+ # 获取环境变量
157+ retrieved_value = os .environ .get (test_var )
158+ print (f"获取环境变量: { test_var } = { retrieved_value } " )
159+
160+ # 2. 使用默认值
161+ non_existent = os .environ .get ("NON_EXISTENT_VAR" , "默认值" )
162+ print (f"不存在的环境变量(使用默认值): { non_existent } " )
163+
164+ # 3. 检查环境变量是否存在
165+ if test_var in os .environ :
166+ print (f"环境变量 { test_var } 存在" )
167+
168+ # 4. 删除环境变量
169+ if test_var in os .environ :
170+ del os .environ [test_var ]
171+ print (f"已删除环境变量: { test_var } " )
172+
173+ # 5. 常用环境变量
174+ print (f"\n 常用环境变量:" )
175+ common_vars = ['PATH' , 'HOME' , 'USER' , 'SHELL' , 'LANG' ]
176+ for var in common_vars :
177+ value = os .environ .get (var , '未设置' )
178+ if len (value ) > 50 :
179+ value = value [:47 ] + "..."
180+ print (f" { var } : { value } " )
181+
182+
183+ def demonstrate_file_operations ():
184+ """演示文件操作相关功能"""
185+ print ("\n " + "=" * 50 )
186+ print ("文件操作演示" )
187+ print ("=" * 50 )
188+
189+ # 1. 创建临时文件进行演示
190+ demo_file = "demo_file.txt"
191+ demo_dir = "demo_directory"
192+
193+ try :
194+ # 创建演示文件
195+ with open (demo_file , 'w' , encoding = 'utf-8' ) as f :
196+ f .write ("这是一个演示文件\n " )
197+ f .write ("用于展示os模块的文件操作功能\n " )
198+
199+ print (f"创建演示文件: { demo_file } " )
200+
201+ # 文件信息
202+ stat_info = os .stat (demo_file )
203+ print (f"文件大小: { stat_info .st_size } 字节" )
204+ print (f"文件权限: { oct (stat_info .st_mode )} " )
205+
206+ # 创建目录
207+ if not os .path .exists (demo_dir ):
208+ os .mkdir (demo_dir )
209+ print (f"创建演示目录: { demo_dir } " )
210+
211+ # 重命名文件
212+ new_name = "renamed_demo.txt"
213+ os .rename (demo_file , new_name )
214+ print (f"文件重命名: { demo_file } -> { new_name } " )
215+
216+ # 移动文件到目录
217+ moved_path = os .path .join (demo_dir , new_name )
218+ os .rename (new_name , moved_path )
219+ print (f"文件移动到: { moved_path } " )
220+
221+ # 列出目录内容
222+ print (f"\n 目录 { demo_dir } 的内容:" )
223+ for item in os .listdir (demo_dir ):
224+ item_path = os .path .join (demo_dir , item )
225+ if os .path .isfile (item_path ):
226+ print (f" 文件: { item } " )
227+ elif os .path .isdir (item_path ):
228+ print (f" 目录: { item } " )
229+
230+ except Exception as e :
231+ print (f"文件操作出错: { e } " )
232+
233+ finally :
234+ # 清理演示文件和目录
235+ try :
236+ if os .path .exists (moved_path ):
237+ os .remove (moved_path )
238+ print (f"\n 清理文件: { moved_path } " )
239+ if os .path .exists (demo_dir ):
240+ os .rmdir (demo_dir )
241+ print (f"清理目录: { demo_dir } " )
242+ except Exception as e :
243+ print (f"清理时出错: { e } " )
244+
245+
246+ def main ():
247+ """主函数 - 运行所有演示"""
248+ print ("Python标准库 - os和sys模块学习" )
249+ print ("本程序演示os和sys模块的常用功能" )
250+
251+ try :
252+ demonstrate_os_module ()
253+ demonstrate_sys_module ()
254+ demonstrate_platform_info ()
255+ demonstrate_environment_operations ()
256+ demonstrate_file_operations ()
257+
258+ print ("\n " + "=" * 50 )
259+ print ("学习要点总结:" )
260+ print ("=" * 50 )
261+ print ("1. os模块主要用于操作系统接口操作" )
262+ print ("2. sys模块提供Python解释器相关信息" )
263+ print ("3. 环境变量可以通过os.environ访问和修改" )
264+ print ("4. 路径操作使用os.path模块更安全" )
265+ print ("5. platform模块提供详细的平台信息" )
266+ print ("6. 文件操作要注意异常处理和资源清理" )
267+
268+ except KeyboardInterrupt :
269+ print ("\n 程序被用户中断" )
270+ except Exception as e :
271+ print (f"\n 程序执行出错: { e } " )
272+ sys .exit (1 )
273+
274+
275+ if __name__ == "__main__" :
276+ main ()
0 commit comments