我编写了一个使用的小python脚本multiprocessing(参见/sf/answers/2931299801/).它在我测试它时起作用:
$ ./forkiter.py
0
1
2
3
4
sum of x+1: 15
sum of 2*x: 20
sum of x*x: 30
Run Code Online (Sandbox Code Playgroud)
但是当我尝试对其进行分析时cProfile,我会得到以下结果:
$ python3.6 -m cProfile -o forkiter.prof ./forkiter.py
0
1
2
3
4
Traceback (most recent call last):
File "/home/bli/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/home/bli/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/bli/lib/python3.6/cProfile.py", line 160, in <module>
main()
File "/home/bli/lib/python3.6/cProfile.py", line 153, in main
runctx(code, globs, None, options.outfile, options.sort)
File "/home/bli/lib/python3.6/cProfile.py", …Run Code Online (Sandbox Code Playgroud) 我multiprocessing正在使用模块,我正在使用UpdateMessage对象(我自己的类),通过multiprocessing.Queue对象发送,在进程之间进行通信.这是类:
class UpdateMessage:
def __init__(self, arrayref, rowslice, colslice, newval):
self.arrayref = arrayref
self.rowslice = rowslice
self.colslice = colslice
self.newval = newval
def do_update(self):
if self.arrayref == 'uL':
arr = uL
elif self.arrayref == 'uR':
arr = uR
else:
raise Exception('UpdateMessage.arrayref neither uL nor uR')
arr[self.rowslice, self.colslice] = self.newval
Run Code Online (Sandbox Code Playgroud)
当我运行脚本时,它完全正常.但是,当我使用cProfile或运行它时profile,它会出现以下错误:
_pickle.PicklingError: Can't pickle <class '__main__.UpdateMessage'>: attribute lookup __main__.UpdateMessage failed
Run Code Online (Sandbox Code Playgroud)
它似乎试图挑选课程,但我不明白为什么会发生这种情况.我的代码没有这样做,没有它就可以正常工作,所以它可能就是multiprocessing模块.但为什么需要腌制UpdateMessage,我该如何修复错误呢?
编辑:这是发送的代码的一部分UpdateMessage(脚本的多个部分执行此操作,但所有都以相同的方式):
msg = UpdateMessage(uLref, refer[0] …Run Code Online (Sandbox Code Playgroud) 使用 Python 的 isinstance 方法时,定义两个类(两个单独的文件中的基类“ClassA”和子类“ClassB”)会产生意外结果。输出似乎受到运行时使用的模块名称(命名空间?)的影响(__main__)。此行为出现在 Python 3.8.5 和 3.10.4 上。
文件 ClassA.py 包含:
class ClassA:
def __init__(self, id):
self.id = id
def __str__(self) -> str:
class_name = type(self).__name__
return f"{class_name} WITH id: {self.id}"
def main():
from ClassB import ClassB
id = 42
for i, instance in enumerate([ClassA(id), ClassB(id)]):
label = f"{type(instance).__name__}:"
print("#" * 50)
print(f"{label} type: {type(instance)}")
label = " " * len(label) # Convert label to appropriate number of spaces
is_a = isinstance(instance, ClassA)
is_b = isinstance(instance, ClassB)
print(f"{label} …Run Code Online (Sandbox Code Playgroud)