0

可能我忽略了一些非常基本的东西。我有一个功能

def execution(command):
    os.system(command)

还有另一个功能

def start_this_thread():
    server_thread = threading.Thread(target=execution, args=(exec_str))
    server_thread.start()

我收到一个错误:

self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 483, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: execution() takes exactly 1 argument (233 given)

显然字符串长度(命令)的长度为 233??

4

3 回答 3

2

好的。。我想通了。。

代替

  server_thread = threading.Thread(target=execution, args=(exec_str))

它应该是

 server_thread = threading.Thread(target=execution, args=(exec_str,))

虽然很想知道为什么?

于 2013-03-07T08:36:17.597 回答
1

args被简单地解释为一系列参数。您传入的(args_str)是一个字符串(因为这对括号被简单地解释为分组,而不是元组构造函数)。因此,字符串作为一个序列扩展为 233 个单独的参数(字符串中的每个字符一个)。

改为使用(args_str,)(注意尾随逗号)来创建单元素元组。

于 2013-03-07T08:43:09.660 回答
0

Your problem is that args gets expanded, which afaik means that exec_string is going from 1 item into 233. Try putting a comma after exec_string to make it a literal tuple instead of parentheses. I'm on mobile right now but will edit tomorrow sometime for formatting and clarity.

In python, (something)==something, but (something,) is a tuple of 1 item with something as the only element.

于 2013-03-07T08:39:10.637 回答