网络编程
位置:首页>> 网络编程>> Python编程>> Python I/O与进程的详细讲解

Python I/O与进程的详细讲解

作者:沙沙罗曼  发布时间:2022-11-27 14:07:15 

标签:python,i/o,进程

I/O

with语句


with context_expression [as target(s)]:
 with-body

context_expression返回值遵从上下文管理协议,包含__enter__()__exit__()方法,as语句的target(s)得到的是__enter__()返回值,执行with-body后会调用上下文管理器的__exit__()方法,使用with语句,可以减轻某些代码编写负担,比如文件读写。

读文件


try:
 f = open('/path/to/file', 'r', encoding='utf8', errors='ignore')
 print(f.read(1024))
finally:
 if f:
   f.close()
# 使用with语句
with open('/path/to/file', 'r') as f:
 print(f.read(1024))

open()方法打开文件模式,默认以utf8格式读取,添加后缀'b'(rb、wb)表示以二进制方式读取,mode有以下几种:

Python I/O与进程的详细讲解

StringIO和BytesIO

StringIO将string按照文件的方式读取和写入,BytesIO将bytes按照文件的的方式读取和写入。

OS

通过OS模块,与操作系统信息交互,如创建、移动、列出文件等等。

序列化

通过内置模块pickle,实现序列化与反序列化,使用json模块完成JSON数据的序列化和反序列化。


import pickle
d = dict(name = 'sha', age = 26)
# 将序列化内容写入文件
with open('dump', 'wb') as f:
 pickle.dump(d, f)
# 从文件中读取序列化内容
with open('dump', 'rb') as f:
 d = pickle.load(f)
print(d) # {'name': 'sha', 'age': 26}

进程与线程

进程

Python调用一次进程fork()会有两次返回,子进程永远返回0,父进程中返回子进程ID。os.fork()不支持windows,multiprocessing模块是跨平台版本的多进程模块。


import os
pid = os.fork() # pid后的代码会在两个进程中分别执行,通过pid值不同判断父子
if pid == 0:
 print('exec in child process')
else:
 print('exec in parent process')
# exec in parent process
# exec in child process

进程池


from multiprocessing import Pool
def say(x):
 print(x)
if __name__ == '__main__':
 p = Pool(4)
 for i in range(5):
   p.apply_async(say, args=(i,))
 p.close()
 p.join()

子进程


import subprocess
print('$ nslookup amsimple.com')
r = subprocess.call(['nslookup', 'amsimple.com'])
print('Exit code:', r)

进程间通信

进程间通信通过Queue与Pipes实现,父进程创建Queue传递给子进程。

线程

Python提供两个模块_thread与threading,前者是低级模块后者是高级模块,对_thread进行了封装。

启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:


import threading
# 新线程执行的代码:
def say():
 print('%s say hello' % threading.current_thread().name)
t = threading.Thread(target=say, name = 'SayThread')
t.start()
t.join()

threading.current_thread()返回但前运行线程的实例,主线程名MainTreed,子线程名在创建时指定。

通过threading.Lock()获取锁,某些需要线程安全的操作,先通过acquire()获取锁,通过release()释放锁。

Python中的线程因为GIL锁,无法真正利用多核。

通过ThreadLocal实现线程级的全局变量,不同线程间相互不影响。


import threading
th_local = threading.local() # th_local会跟线程绑定,不同线程看到的是不同对象

分布式进程

managers模块依靠网络通信,可以把多进程分布到多台机器上。

正则

通过'r'前缀定义正则字符串,通过re模块做正则匹配等操作。


import re
s = r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$'
re.match(s, 'shasharoman@gmail.com')

来源:https://amsimple.com/blog/article/43.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com