当python处于无限循环中时更改值

2024-09-30 04:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这可以用python实现吗? 首先打印一个无限循环,并在循环之间更改值。在

x = 5
while ( true ):
  print x
x = 3 # regain control of the interpreter and set to new value

预期产量:

^{pr2}$

Tags: andofthetotruenewvaluecontrol
3条回答

不,你写的代码是行不通的。将永远不会执行非终止循环之后的语句。在

尝试以下操作:

x = 5
while True:
  if (some-condition):
    x = 3
  print x

或者,使用threading,并在第二个线程中更改x的值:

^{pr2}$

不清楚需要执行此操作的原因,但可以捕获“ctrl-c”事件并输入新值:

x = 5
while True:
    try:
        print x
    except KeyboardInterrupt:
        x = raw_input("Enter new value: ").strip()

我认为这个问题的最佳答案是使用线程,但是有一种方法可以将代码注入正在运行的解释器线程中:

https://fedorahosted.org/pyrasite/

相关问题 更多 >

    热门问题