栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python作业

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python作业

练习题: 使用以上三选一的方式,完成多进程程序同时写操作多个文件。 比如,同时启动三个子进程,分别写三个不同文件 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929012.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号