0
我是新来的线程和多处理。我有一些代码中,我开始一个过程,我想输出显示这样Python线程和字符串
wating....
的一些活动等待状态的代码类同下面这样:
进口线程 进口时间
class ThreadExample(object):
def __init__(self):
self.pause = True
threading.Thread(target=self.second_thread).start()
# Some other processes
print("Waiting", end="")
while self.pause:
time.sleep(1)
print(".", end="")
print("Hooray!")
def second_thread(self):
print("timer started")
time.sleep(3)
self.pause = False
print("timer finished")
if __name__ == "__main__":
ThreadExample()
当运行上述代码时,收到的输出:
timer started
Do something else..timer finished
.
Hooray!
不是一个大的惊喜,除了只有'开始计时器'出现在开头,其余的文本出现在结束瞬间。
如果更改行打印( “ ”结束=“ ”),打印(“。”),I收到以下输出:
timer started
Do something else.
.
timer finished
.
Hooray
其中点出现在1秒为单位
,这是我的意图。
有没有办法让'等待......'在一行中没有结束=“”?
其次,我猜这是与print()函数的内部结构有关,如果不是,我应该以另一种方式执行线程吗?我不认为问题是GIL,因为我尝试了多进程。进程并得到了相同的结果。
注意:在现代Python(3.3及更高版本)中,[print'可以通过'flush = True'在打印后刷新](https://docs.python.org/3/library/functions。 html#print),同时保留'print'功能的全部功能/灵活性。所以'print(end ='。',flush = True)'或'print('。',end ='',flush = True)'也可以。 – ShadowRanger
谢谢,这非常有用。 – VectorVictor