python进程传参踩坑:为何单变量参数被识别为多变量

背景:

新建一个脚本进程,需要如下传参:

fastcsr_input = ['--t1',input_nu_image, '--L4', t1_label_L4]
p_fastcsr = multiprocessing.Process(target=FastCSR_pipeline.main, args=(fastcsr_input))
p_fastcsr.start()
p_fastcsr.join()

脚本FastCSR_pipeline.main函数只接受一个输入变量,但运行时报错:

python TypeError: write() takes exactly 1 argument (but 4 were given)

方案:

折腾半天找到原因multiprocessing.Processargs变量是tuple类型,tuple中若只有一个对象,需要在后面加一个逗号。。

所以修改代码为:

fastcsr_input = ['--t1',input_nu_image, '--L4', t1_label_L4]
p_fastcsr = multiprocessing.Process(target=FastCSR_pipeline.main, args=(fastcsr_input,))
p_fastcsr.start()
p_fastcsr.join()

即可顺利运行

Chenfei Ye
Chenfei Ye
A connectome weaver

The brain’s billions of neurons resemble trees of many species and come in many fantastic shapes. Only the most determined explorers can hope to capture a glimpse of this forest’s interior, and even they see little, and see it poorly.