python 多个线程用于继续循环直到用户输入。帮助理解请求的示例
python multiple threads used to continue loop until user input. Help understanding examples requested
我正在实现一个循环,该循环应该一直持续到用户按照 this page 上的说明按下 Return 键,我才开始工作:
def _input_thread_2( L ):
raw_input()
L.append( None )
#### test _input_thread()
L = []
thread.start_new_thread(_input_thread_2, (L, ))
while True:
time.sleep(1)
print "\nstill going..."
if L:
break
我的问题是下面看似简单的适配为什么不起作用?它不会在按下某个键时退出循环,而是一直循环:
def _input_thread_3( keep_going ):
"""
Input: doesn't matter
Description - When user clicks the return key, this changes the input to the False bool.
"""
raw_input()
keep_going = False
#### test _input_thread()
keep_going = True
thread.start_new_thread(_input_thread_3, (keep_going, ) )
while True:
time.sleep(1)
print "\nstill going..."
if not keep_going:
break
你能帮我理解一下它们之间的区别吗?
In Python, why can a function modify some arguments as perceived by the caller, but not others?
就是这个原因。您的 keep_alive
是不可变的,而列表是可变的。
这是@Hannu 回答的更详细版本。
在上面的两个 _input_thread()
函数中,都会创建一个 "copy" 输入。首先,由于 L
是一个列表(可变的),副本实际上是指向列表的第二个名称 L
。 L
都是不同的列表引用,但内容相同。 .append()
方法更改列表的内容。两个参考文献 L
都看到了。
在第二个版本中,名称 keep_going
的新版本指向(新的)bool(不可变)。所以只有第二个版本被改变了,while
循环永远看不到它。
我正在实现一个循环,该循环应该一直持续到用户按照 this page 上的说明按下 Return 键,我才开始工作:
def _input_thread_2( L ):
raw_input()
L.append( None )
#### test _input_thread()
L = []
thread.start_new_thread(_input_thread_2, (L, ))
while True:
time.sleep(1)
print "\nstill going..."
if L:
break
我的问题是下面看似简单的适配为什么不起作用?它不会在按下某个键时退出循环,而是一直循环:
def _input_thread_3( keep_going ):
"""
Input: doesn't matter
Description - When user clicks the return key, this changes the input to the False bool.
"""
raw_input()
keep_going = False
#### test _input_thread()
keep_going = True
thread.start_new_thread(_input_thread_3, (keep_going, ) )
while True:
time.sleep(1)
print "\nstill going..."
if not keep_going:
break
你能帮我理解一下它们之间的区别吗?
In Python, why can a function modify some arguments as perceived by the caller, but not others?
就是这个原因。您的 keep_alive
是不可变的,而列表是可变的。
这是@Hannu 回答的更详细版本。
在上面的两个 _input_thread()
函数中,都会创建一个 "copy" 输入。首先,由于 L
是一个列表(可变的),副本实际上是指向列表的第二个名称 L
。 L
都是不同的列表引用,但内容相同。 .append()
方法更改列表的内容。两个参考文献 L
都看到了。
在第二个版本中,名称 keep_going
的新版本指向(新的)bool(不可变)。所以只有第二个版本被改变了,while
循环永远看不到它。