使用spyder(Anaconda)写一段代码,但Ipython console没有打印print的内容,如何解决
本帖最后由 Sandwiches 于 2021-10-5 23:24 编辑# -*- coding: utf-8 -*-
"""
Created on Tue Oct5 23:15:22 2021
@author: Administrator
"""
from multiprocessing import Process, Queue
import os
import time
import random
def write(q):
print(f'Process to write: {os.getpid()}')
for value in ['A', 'B', 'C']:
print(f'Put {value} to queue...')
q.put(value)
time.sleep(random.random())
def read(q):
print(f'Process to read: {os.getpid()}')
while True:
value = q.get(True)
print(f'Get {value} from queue.')
def main():
# test queue
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()
if __name__ == '__main__':
main()
这个我记得好像是ipython和jupyter只会监听主进程的输出消息,他不会输出子进程中的内容,你可以讲代码放在pycharm中执行 本帖最后由 Jack2002 于 2021-10-7 00:56 编辑
代码是没问题的,pr.terminate() 强制终止,不推荐这么做,加个判断就能控制其自然退出。
# -*- coding: utf-8 -*-
from multiprocessing import Process, Queue
import os
import time
def write(q):
print(f'Process to write: {os.getpid()}')
for value in ['A', 'B', 'C']:
print(f'Put {value} to queue...')
q.put(value)
time.sleep(0.3)
def read(q):
print(f'Process to read: {os.getpid()}')
while True:
value = q.get(True)
if 'quit' == value:
break
print(f'Get {value} from queue.')
def main():
# test queue
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 启动子进程pr,读取:
pr.start()
# 等待pw结束:
pw.join()
# 退出
q.put('quit')
# pr进程里是死循环,无法等待其结束,只能强行终止:
# pr.terminate()
pr.join()
if __name__ == '__main__':
main()
页:
[1]