python多处理中的字符串参数 [英] String arguments in python multiprocessing
问题描述
我正在尝试将字符串参数传递给进程中的目标函数.某种程度上,字符串被解释为包含字符的参数列表.
I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.
这是代码:
import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Process(target=write, args=('hello'))
p.start()
我得到以下输出:
hello
Process Process-1:
Traceback (most recent call last):
>>> File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/usr/local/lib/python2.5/site-packages/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
TypeError: write() takes exactly 1 argument (5 given)
>>>
我做错了什么?我应该如何传递细绳呢?
What am I doing wrong? How am I supposed to pass a stringn?
谢谢Ariel
推荐答案
这是Python中的常见陷阱-如果您想要一个只有一个元素的元组,则需要指定它实际上是一个元组(而不仅仅是带有方括号的东西)-通过在元素后添加逗号来完成.
This is a common gotcha in Python - if you want to have a tuple with only one element, you need to specify that it's actually a tuple (and not just something with brackets around it) - this is done by adding a comma after the element.
要解决此问题,只需在字符串后的方括号内添加逗号:
To fix this, just put a comma after the string, inside the brackets:
p = multiprocessing.Process(target=write, args=('hello',))
这样,Python将按预期将其识别为具有单个元素的元组.目前,Python将您的代码解释为一个字符串.但是,它以这种特定方式失败了,因为字符串实际上是字符列表.因此,Python认为您希望通过("h","e","l","l","o").这就是为什么它说您给了我5个参数".
That way, Python will recognise it as a tuple with a single element, as intended. Currently, Python is interpreting your code as just a string. However, it's failing in this particular way because a string is effectively list of characters. So Python is thinking that you want to pass ('h', 'e', 'l', 'l', 'o'). That's why it's saying "you gave me 5 parameters".
这篇关于python多处理中的字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!