1. 首页 > IT综合教程 > 正文

IT教程FG352-软件编程基础

一、编程基础概念

软件编程是IT运维人员必备的技能之一,掌握编程基础可以帮助运维人员实现自动化运维、脚本开发等工作。本教程以Python语言为例,介绍编程的基础知识和实践技巧。

学习交流加群风哥微信: itpux-com,在FGedu企业的运维开发中,我们大量使用Python进行自动化脚本开发、数据处理和系统管理,大大提高了运维效率。

1.1 编程语言概述

# 编程语言分类

编程语言类型:
1. 解释型语言
– Python、JavaScript、Ruby
– 逐行解释执行
– 开发效率高,运行效率较低

2. 编译型语言
– C、C++、Go
– 编译后执行
– 运行效率高,开发效率较低

3. 混合型语言
– Java、C#
– 编译为字节码,虚拟机执行
– 平衡开发和运行效率

# Python语言特点
优点:
– 语法简洁,易于学习
– 丰富的标准库和第三方库
– 跨平台支持
– 社区活跃,资源丰富

缺点:
– 运行速度较慢
– 全局解释器锁(GIL)限制多线程性能
– 移动端开发支持较弱

# Python应用场景
应用领域:
– 自动化运维脚本
– 数据分析和可视化
– 机器学习和人工智能
– Web开发
– 网络爬虫
– 测试自动化

# Python版本选择
Python 2.x vs Python 3.x:
– Python 2.x 已停止维护
– Python 3.x 是当前主流版本
– 建议使用 Python 3.8+

# 查看Python版本
$ python3 –version
Python 3.9.7

$ python3 -c “import sys; print(sys.version)”
3.9.7 (default, Sep 16 2021, 16:59:28)
[Clang 10.0.0 ]

二、Python编程基础

2.1 变量与数据类型

# Python变量与数据类型

# 1. 变量定义
# Python是动态类型语言,不需要声明变量类型
name = “FGedu” # 字符串
age = 10 # 整数
price = 99.99 # 浮点数
is_active = True # 布尔值

print(f”名称: {name}, 年龄: {age}, 价格: {price}, 激活: {is_active}”)

# 输出
名称: FGedu, 年龄: 10, 价格: 99.99, 激活: True

# 2. 数据类型
# 查看变量类型
print(type(name)) #
print(type(age)) #
print(type(price)) #
print(type(is_active)) #

# 3. 字符串操作
str1 = “Hello”
str2 = “FGedu”

# 字符串拼接
result = str1 + ” ” + str2
print(result) # Hello FGedu

# 字符串格式化
name = “风哥”
age = 35
print(f”姓名: {name}, 年龄: {age}”)
print(“姓名: {}, 年龄: {}”.format(name, age))

# 字符串方法
text = ” fgedu.net.cn ”
print(text.strip()) # 去除空格: fgedu.net.cn
print(text.upper()) # 转大写: FGEDU.NET.CN
print(text.lower()) # 转小写: fgedu.net.cn
print(text.replace(“fgedu”, “FGEDU”)) # 替换: FGEDU.net.cn

# 4. 列表操作
servers = [“web01”, “web02”, “db01”, “cache01”]

# 访问元素
print(servers[0]) # web01
print(servers[-1]) # cache01
print(servers[1:3]) # [‘web02’, ‘db01’]

# 添加元素
servers.append(“web03”)
servers.insert(0, “lb01”)

# 删除元素
servers.remove(“cache01”)
del servers[0]

# 列表方法
print(len(servers)) # 列表长度: 4
print(“web01” in servers) # 检查元素: True

# 5. 字典操作
server_info = {
“hostname”: “fgedu-web01”,
“ip”: “192.168.1.10”,
“cpu”: 8,
“memory”: 16,
“disk”: 500
}

# 访问元素
print(server_info[“hostname”]) # fgedu-web01
print(server_info.get(“ip”)) # 192.168.1.10

# 添加/修改元素
server_info[“os”] = “CentOS 7”
server_info[“cpu”] = 16

# 删除元素
del server_info[“disk”]

# 遍历字典
for key, value in server_info.items():
print(f”{key}: {value}”)

# 输出
hostname: fgedu-web01
ip: 192.168.1.10
cpu: 16
memory: 16
os: CentOS 7

# 6. 元组和集合
# 元组(不可变)
coordinates = (10, 20, 30)
print(coordinates[0]) # 10

# 集合(去重)
unique_servers = {“web01”, “web02”, “web01”, “db01”}
print(unique_servers) # {‘web01’, ‘web02’, ‘db01’}

2.2 控制流程

# Python控制流程

# 1. 条件判断
score = 85

if score >= 90:
grade = “A”
elif score >= 80:
grade = “B”
elif score >= 70:
grade = “C”
elif score >= 60:
grade = “D”
else:
grade = “F”

print(f”分数: {score}, 等级: {grade}”)

# 输出
分数: 85, 等级: B

# 2. 循环
# for循环
servers = [“web01”, “web02”, “db01″]

for server in servers:
print(f”检查服务器: {server}”)

# 输出
检查服务器: web01
检查服务器: web02
检查服务器: db01

# 使用range
for i in range(5):
print(f”循环次数: {i}”)

# 输出
循环次数: 0
循环次数: 1
循环次数: 2
循环次数: 3
循环次数: 4

# while循环
count = 0
while count < 5: print(f"计数: {count}") count += 1 # 输出 计数: 0 计数: 1 计数: 2 计数: 3 计数: 4 # 3. 循环控制 # break和continue for i in range(10): if i == 3: continue # 跳过3 if i == 7: break # 在7时退出 print(i) # 输出 0 1 2 4 5 6 # 4. 列表推导式 # 生成平方数列表 squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # 带条件的列表推导式 even_squares = [x**2 for x in range(10) if x % 2 == 0] print(even_squares) # [0, 4, 16, 36, 64] # 5. 字典推导式 # 生成服务器信息字典 servers = ["web01", "web02", "db01"] server_dict = {server: f"192.168.1.{10+i}" for i, server in enumerate(servers)} print(server_dict) # {'web01': '192.168.1.10', 'web02': '192.168.1.11', 'db01': '192.168.1.12'}

三、数据结构与算法

3.1 常用数据结构

# Python数据结构

# 1. 栈(Stack)
class Stack:
def __init__(self):
self.items = []

def push(self, item):
self.items.append(item)

def pop(self):
return self.items.pop()

def peek(self):
return self.items[-1]

def is_empty(self):
return len(self.items) == 0

def size(self):
return len(self.items)

# 使用栈
stack = Stack()
stack.push(“任务1”)
stack.push(“任务2”)
stack.push(“任务3″)

print(f”栈顶元素: {stack.peek()}”)
print(f”弹出元素: {stack.pop()}”)
print(f”栈大小: {stack.size()}”)

# 输出
栈顶元素: 任务3
弹出元素: 任务3
栈大小: 2

# 2. 队列(Queue)
from collections import deque

class Queue:
def __init__(self):
self.items = deque()

def enqueue(self, item):
self.items.append(item)

def dequeue(self):
return self.items.popleft()

def is_empty(self):
return len(self.items) == 0

def size(self):
return len(self.items)

# 使用队列
queue = Queue()
queue.enqueue(“请求1”)
queue.enqueue(“请求2”)
queue.enqueue(“请求3″)

print(f”队首元素: {queue.dequeue()}”)
print(f”队列大小: {queue.size()}”)

# 输出
队首元素: 请求1
队列大小: 2

# 3. 链表
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node

def display(self):
current = self.head
while current:
print(current.data, end=” -> “)
current = current.next
print(“None”)

# 使用链表
ll = LinkedList()
ll.append(“节点1”)
ll.append(“节点2”)
ll.append(“节点3”)
ll.display()

# 输出
节点1 -> 节点2 -> 节点3 -> None

# 4. 二叉树
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None

class BinaryTree:
def __init__(self):
self.root = None

def insert(self, value):
if not self.root:
self.root = TreeNode(value)
else:
self._insert_recursive(self.root, value)

def _insert_recursive(self, node, value):
if value < node.value: if node.left is None: node.left = TreeNode(value) else: self._insert_recursive(node.left, value) else: if node.right is None: node.right = TreeNode(value) else: self._insert_recursive(node.right, value) def inorder_traversal(self, node): if node: self.inorder_traversal(node.left) print(node.value, end=" ") self.inorder_traversal(node.right) # 使用二叉树 bt = BinaryTree() bt.insert(5) bt.insert(3) bt.insert(7) bt.insert(1) bt.insert(9) print("中序遍历:") bt.inorder_traversal(bt.root) # 输出 中序遍历: 1 3 5 7 9

四、文件操作

4.1 文件读写

# Python文件操作

# 1. 文件读取
# 读取整个文件
with open(‘/etc/hosts’, ‘r’) as f:
content = f.read()
print(content)

# 输出
127.0.0.1 fgedudb fgedudb.localdomain
::1 fgedudb fgedudb.localdomain fgedudb6 fgedudb6.localdomain6
192.168.1.10 fgedu-web01
192.168.1.11 fgedu-web02

# 逐行读取
with open(‘/etc/hosts’, ‘r’) as f:
for line in f:
print(line.strip())

# 读取到列表
with open(‘/etc/hosts’, ‘r’) as f:
lines = f.readlines()
print(f”总行数: {len(lines)}”)

# 输出
总行数: 4

# 2. 文件写入
# 写入文件(覆盖)
with open(‘/tmp/test.txt’, ‘w’) as f:
f.write(“Hello FGedu\n”)
f.write(“这是测试文件\n”)

# 追加写入
with open(‘/tmp/test.txt’, ‘a’) as f:
f.write(“追加的内容\n”)

# 写入多行
lines = [“行1\n”, “行2\n”, “行3\n”]
with open(‘/tmp/test.txt’, ‘a’) as f:
f.writelines(lines)

# 3. JSON文件操作
import json

# 写入JSON
config = {
“server”: {
“host”: “192.168.1.10”,
“port”: 8080
},
“database”: {
“host”: “192.168.1.20”,
“port”: 3306,
“name”: “fgedu_db”
}
}

with open(‘/tmp/config.json’, ‘w’) as f:
json.dump(config, f, indent=2)

# 读取JSON
with open(‘/tmp/config.json’, ‘r’) as f:
config = json.load(f)
print(f”服务器: {config[‘server’][‘host’]}:{config[‘server’][‘port’]}”)

# 输出
服务器: 192.168.1.10:8080

# 4. CSV文件操作
import csv

# 写入CSV
data = [
[“服务器”, “IP地址”, “状态”],
[“web01”, “192.168.1.10”, “运行中”],
[“web02”, “192.168.1.11”, “运行中”],
[“db01”, “192.168.1.20”, “运行中”]
]

with open(‘/tmp/servers.csv’, ‘w’, newline=”) as f:
writer = csv.writer(f)
writer.writerows(data)

# 读取CSV
with open(‘/tmp/servers.csv’, ‘r’) as f:
reader = csv.reader(f)
for row in reader:
print(row)

# 输出
[‘服务器’, ‘IP地址’, ‘状态’]
[‘web01’, ‘192.168.1.10’, ‘运行中’]
[‘web02’, ‘192.168.1.11’, ‘运行中’]
[‘db01’, ‘192.168.1.20’, ‘运行中’]

# 5. 文件路径操作
import os

# 获取当前目录
print(f”当前目录: {os.getcwd()}”)

# 列出目录内容
files = os.listdir(‘/tmp’)
print(f”文件数量: {len(files)}”)

# 创建目录
os.makedirs(‘/tmp/fgedu/test’, exist_ok=True)

# 检查文件是否存在
if os.path.exists(‘/etc/hosts’):
print(“文件存在”)

# 获取文件信息
stat = os.stat(‘/etc/hosts’)
print(f”文件大小: {stat.st_size} 字节”)

# 输出
当前目录: /root
文件数量: 125
文件存在
文件大小: 256 字节

五、异常处理

5.1 异常捕获与处理

# Python异常处理

# 1. 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f”错误: {e}”)

# 输出
错误: division by zero

# 2. 多个异常处理
try:
with open(‘/nonexistent/file.txt’, ‘r’) as f:
content = f.read()
except FileNotFoundError:
print(“文件不存在”)
except PermissionError:
print(“权限不足”)
except Exception as e:
print(f”未知错误: {e}”)

# 输出
文件不存在

# 3. try-except-else-finally
try:
result = 10 / 2
except ZeroDivisionError:
print(“除零错误”)
else:
print(f”结果: {result}”)
finally:
print(“清理工作”)

# 输出
结果: 5.0
清理工作

# 4. 自定义异常
class ServerError(Exception):
def __init__(self, server_name, error_code):
self.server_name = server_name
self.error_code = error_code
super().__init__(f”服务器 {server_name} 错误: {error_code}”)

def check_server(server_name):
if server_name == “error_server”:
raise ServerError(server_name, 500)
return “正常”

try:
status = check_server(“error_server”)
except ServerError as e:
print(e)

# 输出
服务器 error_server 错误: 500

# 5. 上下文管理器
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None

def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file

def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
if exc_type:
print(f”发生异常: {exc_val}”)
return True

with FileManager(‘/tmp/test.txt’, ‘w’) as f:
f.write(“测试内容”)

# 6. 日志记录
import logging

# 配置日志
logging.basicConfig(
level=logging.INFO,
format=’%(asctime)s – %(name)s – %(levelname)s – %(message)s’,
filename=’/tmp/app.log’
)

logger = logging.getLogger(‘FGeduApp’)

# 记录日志
logger.debug(“调试信息”)
logger.info(“普通信息”)
logger.warning(“警告信息”)
logger.error(“错误信息”)
logger.critical(“严重错误”)

# 异常日志
try:
result = 10 / 0
except Exception as e:
logger.exception(“发生异常”)

# 查看日志
$ cat /tmp/app.log
2026-04-03 10:00:00,123 – FGeduApp – INFO – 普通信息
2026-04-03 10:00:00,124 – FGeduApp – WARNING – 警告信息
2026-04-03 10:00:00,125 – FGeduApp – ERROR – 错误信息
2026-04-03 10:00:00,126 – FGeduApp – CRITICAL – 严重错误
2026-04-03 10:00:00,127 – FGeduApp – ERROR – 发生异常
Traceback (most recent call last):
File ““, line 2, in
ZeroDivisionError: division by zero

六、编程最佳实践

6.1 代码规范

# Python编程最佳实践

# 1. 命名规范
# 变量名:小写,下划线分隔
server_name = “fgedu-web01”
max_connections = 100

# 常量:大写,下划线分隔
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30

# 函数名:小写,下划线分隔
def get_server_status(server_name):
pass

# 类名:驼峰命名
class ServerManager:
pass

# 2. 函数设计
def calculate_disk_usage(path, threshold=80):
“””
计算磁盘使用率

Args:
path: 磁盘路径
threshold: 告警阈值(默认80%)

Returns:
tuple: (使用率, 是否超过阈值)

Raises:
FileNotFoundError: 路径不存在
“””
import shutil

if not os.path.exists(path):
raise FileNotFoundError(f”路径不存在: {path}”)

usage = shutil.disk_usage(path)
percent = (usage.used / usage.total) * 100

return percent, percent > threshold

# 使用函数
usage, is_warning = calculate_disk_usage(‘/’)
print(f”磁盘使用率: {usage:.2f}%”)

# 输出
磁盘使用率: 45.67%

# 3. 类设计
class ServerMonitor:
“””服务器监控类”””

def __init__(self, hostname, ip):
self.hostname = hostname
self.ip = ip
self._status = None

@property
def status(self):
“””获取服务器状态”””
return self._status

@status.setter
def status(self, value):
“””设置服务器状态”””
if value not in [‘running’, ‘stopped’, ‘unknown’]:
raise ValueError(“无效的状态值”)
self._status = value

def check_health(self):
“””检查服务器健康状态”””
import subprocess
try:
result = subprocess.run(
[‘ping’, ‘-c’, ‘1’, self.ip],
capture_output=True,
timeout=5
)
self.status = ‘running’ if result.returncode == 0 else ‘stopped’
except Exception:
self.status = ‘unknown’

return self.status

def __str__(self):
return f”Server({self.hostname}, {self.ip}, {self.status})”

# 使用类
monitor = ServerMonitor(“fgedu-web01”, “192.168.1.10”)
status = monitor.check_health()
print(monitor)

# 输出
Server(fgedu-web01, 192.168.1.10, running)

# 4. 代码组织
# server_utils.py
“””
服务器工具模块

提供服务器管理相关的工具函数
“””

import os
import subprocess
from typing import List, Dict, Optional

def get_running_services() -> List[str]:
“””获取运行中的服务列表”””
result = subprocess.run(
[‘systemctl’, ‘list-units’, ‘–type=service’, ‘–state=running’],
capture_output=True,
text=True
)
return result.stdout.splitlines()

def check_port_open(host: str, port: int, timeout: int = 5) -> bool:
“””检查端口是否开放”””
import socket
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
result = s.connect_ex((host, port))
return result == 0
except Exception:
return False

# 5. 单元测试
import unittest

class TestServerUtils(unittest.TestCase):
def setUp(self):
“””测试前准备”””
self.test_host = “fgedudb”
self.test_port = 22

def test_check_port_open(self):
“””测试端口检查”””
result = check_port_open(self.test_host, self.test_port)
self.assertTrue(result)

def test_check_port_closed(self):
“””测试关闭端口检查”””
result = check_port_open(self.test_host, 9999)
self.assertFalse(result)

if __name__ == ‘__main__’:
unittest.main()

# 运行测试
$ python test_server_utils.py
..
———————————————————————-
Ran 2 tests in 0.012s

OK

总结

软件编程基础是IT运维人员必备的技能,掌握Python编程可以帮助实现自动化运维、脚本开发等工作。本教程详细介绍了Python的基础语法、数据结构、文件操作、异常处理和编程最佳实践。

更多学习教程www.fgedu.net.cn,在实际工作中,建议多练习编程,从简单的脚本开始,逐步提高编程能力。

风哥风哥提示:编程最重要的是实践,多写代码、多调试、多总结,才能快速提高编程能力。

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息