PYTHON基础技能 – 15个Python进阶操作系统交互高级命令
今天我们要来探索那些让程序与操作系统无缝对接的高级命令!让我们一起把Python变成操作系统的隐形指挥官吧!
1. 系统调用:os模块的魔法杖
想象一下,用一行Python代码就能执行系统命令,是不是很酷?来看os.system()
的小把戏。
import os
os.system("echo 'Hello, OS!'");
这段代码就像是对操作系统说:“嘿,朋友,帮我打印这句话。” 输出:“Hello, OS!” 但记得,它会打开一个新的shell进程,所以要谨慎使用哦!
2. 目录间的舞蹈:os.path
文件路径就像家的地址,os.path
能帮你轻松管理它们。
current_dir = os.getcwd() # 像不像问:“我现在在哪?”
print(current_dir)
new_folder = "my_new_folder"
os.makedirs(new_folder) # “我要在这里建个新家!”
3. 文件的搬运工:shutil
搬家不求人,shutil
来帮忙。移动文件?小事一桩。
import shutil
file_to_move = "old_file.txt"
new_location = "my_new_folder/" + file_to_move
shutil.move(file_to_move, new_location) # 文件搬家,就这么简单。
4. 文件的读写艺术家:open()
Python的内置函数open()
,是打开文件的钥匙,读写文件的魔法书。
with open("my_file.txt", "w") as file:
file.write("这是我的第一条信息。\n你好,世界!")
# 阅读时间:
with open("my_file.txt", "r") as file:
content = file.read()
print(content)
写入后读取,就像在和文件对话一样!
5. 批处理文件名:glob
想要批量处理文件?glob
让你一网打尽。
import glob
for file in glob.glob("*.txt"): # 找到所有.txt文件
print(file) # 每个文件名,一个接一个。
这招对批量处理图片、文档超实用!
6. 进程的交响乐:multiprocessing
单线程太孤单?multiprocessing
让你的程序并行运行,效率飞起来!
from multiprocessing import Process
def worker(num):
"""小小工人"""
print(f'Worker {num} is working.')
if __name__ == "__main__":
processes = []
for i in range(3):
p = Process(target=worker, args=(i,))
processes.append(p)
p.start()
每个Process
就是一个小工人,同时工作,效率杠杠的!
7. 定时任务:schedule
想要程序定时执行任务?schedule
模块来帮忙。
import schedule
import time
def job():
print("I'm doing a job at scheduled time.")
schedule.every(1).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
就像设置闹钟,让Python自动执行任务。
8. 环境变量的探秘:os.environ
环境变量藏着很多秘密,os.environ
帮你揭开面纱。
print(os.environ.get('PATH')) # 看看PATH变量,了解系统搜索可执行文件的路径。
想知道系统的小秘密?就这么简单。
9. 文件压缩与解压:zipfile/tarfile
压缩文件,节省空间,zipfile
和tartfile
是好帮手。
import zipfile
with zipfile.ZipFile("my_archive.zip", 'w') as zipf:
zipf.write("my_file.txt") # 压缩文件
zipf.printdir() # 查看压缩包内容
with zipfile.ZipFile("my_archive.zip", 'r') as zipf:
zipf.extractall("extracted_files") # 解压文件到指定目录
压缩解压,轻松搞定!
10. 优雅的错误处理:try…except
在操作系统的丛林里,错误难免,优雅处理是关键。
try:
# 尝试执行的危险动作
os.remove("nonexistent_file.txt")
except FileNotFoundError:
print("文件不存在,别担心,我不会哭。")
遇到错误不慌张,从容应对,程序更健壮。
11. 文件的高级遍历:os.scandir()
比os.listdir()
更强大的目录扫描工具。
with os.scandir(".") as entries:
for entry in entries:
if entry.is_file():
print(entry.name)
不仅列出文件名,还能获取更多信息,如是否是文件或目录。
12. 符号链接的创建:os.symlink()
想玩链接游戏?os.symlink()
让你的文件像快捷方式一样存在。
os.symlink("source_file.txt", "symbolic_link.txt") # 创建符号链接
一个链接,两处访问,神奇不?
13. 文件权限的探索:os.access()
安全第一,检查文件权限再操作。
if os.access("a_file.txt", os.R_OK): # 检查读权限
print("我可以读这个文件。")
确保操作前有权限,避免尴尬。
14. 管道与重定向:subprocess
高级玩家必备,subprocess
模块让你直接控制命令行输入输出。
import subprocess
output = subprocess.check_output(["ls", "-l"]) # 类似于os.system,但更强大
print(output.decode()) # 解码输出,显示文件列表
管道和重定向,都在这里实现,强大无比。
15. 终端的色彩魔术:termcolor
给终端加点颜色,让输出更生动。
from termcolor import colored
print(colored("Python编程,彩色生活!", "cyan", attrs=["bold"]))
单调的黑白,瞬间变得活泼起来!
高级概念与应用
16. 进程间通信(IPC):Pipe与Queue
在多进程编程中,进程间的通信至关重要。Python提供了multiprocessing.Pipe
和multiprocessing.Queue
来帮助进程共享数据。
Pipe
from multiprocessing import Process, Pipe
def sender(conn):
conn.send(['hello', 'world']) # 发送消息
conn.close()
def receiver(conn):
print(conn.recv()) # 接收消息
conn.close()
parent_conn, child_conn = Pipe()
p1 = Process(target=sender, args=(child_conn,))
p2 = Process(target=receiver, args=(parent_conn,))
p1.start()
p2.start()
p1.join()
p2.join()
Queue
队列是另一种更安全的进程间通信方式,支持多个生产者和消费者模型。
from multiprocessing import Process, Queue
def writer(q):
q.put('消息来了!')
def reader(q):
print(q.get()) # 阻塞直到有消息
q = Queue()
p1 = Process(target=writer, args=(q,))
p2 = Process(target=reader, args=(q,))
p1.start()
p2.start()
p1.join()
p2.join()
17. 守护进程:后台运行的勇士
在多进程应用中,有时需要一些进程在主进程结束后继续运行,这就是守护进程的作用。
from multiprocessing import Process
class BackgroundTask(Process):
def run(self):
while True:
print("我在后台默默工作...")
time.sleep(2)
background = BackgroundTask(daemon=True) # 设置为守护进程
background.start()
18. 信号处理:响应操作系统信号
Python可以处理操作系统发送的信号,比如Ctrl+C中断信号。
import signal
import os
def signal_handler(sig, frame):
print('捕获到信号:', sig)
exit(0)
signal.signal(signal.SIGINT, signal_handler) # 注册信号处理器
print('PID:', os.getpid())
input('等待中断...')
19. 上下文管理器:with语句的魔力
Python的上下文管理协议通过with
语句,可以自动管理资源,比如自动关闭文件。
with open('test.txt', 'w') as f:
f.write('Hello, context manager!')
# 文件在这里自动关闭,无需f.close()
20. 异步编程:asyncio
最后,我们不能不提异步编程,它是现代Python处理I/O密集型任务的利器。
import asyncio
async def hello(i):
print(f'Hello, world {i}')
await asyncio.sleep(1) # 异步等待
tasks = [hello(i) for i in range(3)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
通过这些深入探讨,你的Python编程技能应该已经更加全面,不仅限于基础的操作系统交互,还涵盖了高级的并发与异步编程。