0

import multiprocessing as mp
import os

def cube(num):
    print(os.getpid())
    print("Cube is {}".format(num*num*num))

def square(num):
    print(os.getpid())
    print("Square is {}".format(num*num))

if __name__ == "__main__":
    p1 = mp.Process(target = cube, args = (3,))
    p2 = mp.Process(target = square, args = (4,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print("Done")

我正在使用该multiprocessing模块,但我无法使用该模块打印函数的任何输出。

我什至尝试stdout使用该sys模块刷新。

4

1 回答 1

0

“为什么multiprocessing模块没有产生预期的结果?

为什么?

因为它崩溃了。

问题的 MWE/MCVE 表示有错误的代码。它崩溃并且与以下内容无关sys.stdout.flush()

>>> cube(  4 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cube
NameError: global name 'os' is not defined

解决方案 :

>>> import os   # be it in the __main__ or in the def()-ed functions...

>>> cube(  4 )
14165
Cube is 64

并且mp.Process()基于您的 python-process 实例的副本也将停止崩溃。


有效的 MCVE:

(base) Fri May 29 14:29:33 $ conda activate py3
(py3) Fri May 29 14:34:55 $ python StackOverflow_mp.py
This is ____6745::__main__
This is ____6746::PID
This is ____6747::PID
Cube(__3) is _______27.
Square(__4) is _______16.
Done.
Works.
Q.E.D.

import multiprocessing as mp
import os
import sys
import time

def cube( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Cube({0:_>3d}) is {1:_>9d}.".format( num, num*num*num ) )
    sys.stdout.flush()

def square( num ):
    print( "This is {0:_>8d}::PID".format( os.getpid() ) )
    print( "Square({0:_>3d}) is {1:_>9d}.".format( num, num*num ) )
    sys.stdout.flush()

if __name__ == "__main__":
    print( "This is {0:_>8d}::__main__".format( os.getpid() ) )
    p1 = mp.Process( target = cube,   args = (3, ) )
    p2 = mp.Process( target = square, args = (4, ) )
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    time.sleep( 1 )

    print( "Done.\nWorks.\nQ.E.D." )

我复制并粘贴了您的确切代码。但是我仍然没有使用多处理库从被调用函数中获得输出
Kartikeya Agarwal 47 分钟前

所以,
- 我打开了一个新的终端进程,
- 我复制了conda activate py3命令
- 我点击Enter让它运行,以使python3生态系统上线。
- 我再次重新启动了解决方案证明python StackOverflow_mp.py-
我点击Enter让它运行
- 我看到它的工作方式与上次一样。
- 我怀疑问题出在提供的两次(重新)验证的解决方案证明方面,是吗?
量子点

(py3) Fri May 29 19:53:58 $ python StackOverflow_mp.py
This is ___27202::__main__
This is ___27203::PID
Cube(__3) is _______27.
This is ___27204::PID
Square(__4) is _______16.
Done
于 2020-05-28T18:11:09.780 回答