String arguments in python multiprocessing

前端 未结 3 496
生来不讨喜
生来不讨喜 2021-02-01 01:54

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.

This

相关标签:
3条回答
  • 2021-02-01 02:19

    Change args=('hello') to args=('hello',) or even better args=['hello']. Otherwise parentheses don't form a sequence.

    0 讨论(0)
  • 2021-02-01 02:31

    You have to pass

    p = multiprocessing.Process(target=write, args=('hello',))
    

    Notice the comma! Otherwise it is interpreted as a simple string and not as a 1 element tuple.

    0 讨论(0)
  • 2021-02-01 02:34

    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',))
    

    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".

    0 讨论(0)
提交回复
热议问题