1 Star 0 Fork 1

aliao/stdpython

forked from pish7/stdpython 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
out2.py 1.62 KB
一键复制 编辑 原始数据 按行查看 历史
pish7 提交于 2023-10-05 21:56 +08:00 . python
import time
import multiprocessing
#一个可调用对象可用作子进程运行
def clock(interval):
while True:
print("P1: The time is {}".format(time.ctime()))
time.sleep(interval)
#通过继承 multiprocessing.Process 也可以定义一个子进程
class ClockProcess(multiprocessing.Process):
def __init__(self, interval):
multiprocessing.Process.__init__(self)
self.interval = interval
#重新定义 run 函数(进程启动时运行的函数)
def run(self):
while True:
print("P2: The time is {}".format(time.ctime()))
time.sleep(self.interval)
# 打开程序第一个参数是一个列表(程序名称,参数)
# 第二个参数是缓冲区大小
# stdin,stdout是设置是否打开这些管道,如果他的值是subprocess.PIPE的话,
# 就会打开,同stdin一样的还有stderr
# child = subprocess.Popen(["python","in.py"], bufsize=1024, stdin=subprocess.PIPE,
# stdout=subprocess.PIPE)
# i = 0
# while True:
# if i > 10:
# break
# else:
# i += 1
# child.stdin.write(str(i).encode())
# child.stdin.write(b"\n")
# child.stdin.write(str(i+1).encode())
# child.stdin.write(b"\n")
# child.stdin.flush()
# fb = child.stdout.readline()
# print(fb.decode().strip())
# sleep(1)
# child.kill()
if __name__ == "__main__":
#创建一个子进程
p1 = multiprocessing.Process(target=clock, args=(5,))
p2 = ClockProcess(5)
#后台进程
p1.daemon = True
p2.daemon = True
#启动子进程
p1.start()
p2.start()
#因为两个子进程是后台进程,所以主进程不能退出,否则这些子进程也将退出
input()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/aliaodc/stdpython.git
git@gitee.com:aliaodc/stdpython.git
aliaodc
stdpython
stdpython
master

搜索帮助