练习题: 使用以上三选一的方式,完成多进程程序同时写操作多个文件。 比如,同时启动三个子进程,分别写三个不同文件 A文件中存储随机大写字母 B文件中存储随机小写字母 C文件中存储随机数字
import time
from multiprocessing import Process #多进程模块
import random
def fun():
count = 0
while True:
with open("xiaoxie.txt", "w+") as f:
for i in range(5):
buff2 = chr(random.randrange(97, 122))
f.write(buff2)
with open("xiaoxie.txt", "r+") as f:
print(f.read())
time.sleep(1)
count +=1
if count >=10:
break
def fun2():
count = 0
while True:
with open("shuzi.txt", "w+") as f:
for i in range(5):
buff1 = chr(random.randrange(48, 57))
f.write(buff1)
with open("shuzi.txt", "r+") as f:
print(f.read())
time.sleep(1)
count += 1
if count >= 10:
break
def main():
pid = Process(target=fun)
pid.start()
pid2 = Process(target=fun2)
pid2.start()
count = 0
while True:
with open("Daxie.txt","w+") as f:
for i in range(5):
buff = chr(random.randrange(65,91))
f.write(buff)
with open("Daxie.txt","r+") as f:
print(f.read())
time.sleep(1)
count += 1
if count >= 10:
break
if __name__ == '__main__': #给程序一个入口
main() #入口函数调用
输出结果:
D:Pythonpython.exe D:/LearnPython/2022517/多进程.py HYKOT nmhyo 33834 FEJJB kjvgr 44251 YSFOD dfiys 87740 INEQH blcef 02677 XNSFI 02686 qawol ASCVC fhehx 64667 GYZEY tsqfx 58850 ILADK qjulg 08561 MDWAF pamxk 06183 YLQPV 26746 rjfna 进程已结束,退出代码为 0



