脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python I/O与进程的详细讲解

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

2021-06-05 00:39沙沙罗曼 Python

今天小编就为大家分享一篇关于Python I/O与进程的详细讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

I/O

with语句

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

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

读文件

?
1
2
3
4
5
6
7
8
9
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数据的序列化和反序列化。

?
1
2
3
4
5
6
7
8
9
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模块是跨平台版本的多进程模块。

?
1
2
3
4
5
6
7
8
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

进程池

?
1
2
3
4
5
6
7
8
9
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()

子进程

?
1
2
3
4
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()开始执行:

?
1
2
3
4
5
6
7
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实现线程级的全局变量,不同线程间相互不影响。

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

分布式进程

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

正则

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

?
1
2
3
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

延伸 · 阅读

精彩推荐