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?
谢谢,阿里
推荐答案
这是 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屋!