为什么 multiprocessing.apply_async 解压一个字符串作为参数?
Why is multiprocessing.apply_async unpacking a string as arguments?
我正在尝试进行一些多处理。
import multiprocessing
with multiprocessing.Pool() as pool:
pool.apply_async(func,('some string'))
我收到一个错误:
TypeError: func() takes 1 positional arguments but 261 were given
这非常可疑,因为我用作参数的字符串有 260 个字符。
有谁知道为什么会这样以及如何解决?
根据Python docs(强调我的!),
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
因此,表达式 ('a')
实际上是在创建一个值为 'a'
的字符串,而表达式 ('a',)
是在创建一个包含单个字符串元素 'a'
的元组。
也就是说,您可以将代码重构为
import multiprocessing
with multiprocessing.Pool() as pool:
pool.apply_async(func, ('some string',))
我正在尝试进行一些多处理。
import multiprocessing
with multiprocessing.Pool() as pool:
pool.apply_async(func,('some string'))
我收到一个错误:
TypeError: func() takes 1 positional arguments but 261 were given
这非常可疑,因为我用作参数的字符串有 260 个字符。
有谁知道为什么会这样以及如何解决?
根据Python docs(强调我的!),
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
因此,表达式 ('a')
实际上是在创建一个值为 'a'
的字符串,而表达式 ('a',)
是在创建一个包含单个字符串元素 'a'
的元组。
也就是说,您可以将代码重构为
import multiprocessing
with multiprocessing.Pool() as pool:
pool.apply_async(func, ('some string',))