Python中语句的执行可以延迟吗?
我希望它运行第一行 print 1 然后等待 1 秒运行第二个命令 print 2 等。
伪代码:
print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4
I want it to run the first line print 1 then wait 1 second to run the second command print 2, etc.
Pseudo-code:
print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
time.sleep(秒)
time.sleep(seconds)
所有答案都假设您想要或可以在每行之后手动插入
time.sleep
,但您可能想要一种自动方式来对大量代码行执行此操作,例如考虑此代码如果如果你想延迟每行的执行,要么你可以在每行之前手动插入
time.sleep
,这样既麻烦又容易出错,也可以使用sys.settrace
来在执行每行之前调用您自己的函数,并且在该回调中您可以延迟执行,因此无需在每个地方手动插入 time.sleep 并乱扔代码,您可以这样做而不需要跟踪输出:
跟踪输出是:
您可以根据需要进一步调整它,也可以检查行内容,最重要的是,这很容易禁用并且适用于任何代码。
All the answers have assumed that you want or can manually insert
time.sleep
after each line, but may be you want a automated way to do that for a large number of lines of code e.g. consider this codeIf you want to delay execution of each line, either you can manually insert
time.sleep
before each line which is cumbersome and error-prone, instead you can usesys.settrace
to get you own function called before each line is executed and in that callback you can delay execution, so without manually insertingtime.sleep
at every place and littering code, you can do this insteadWithout trace output is:
With trace output is:
You can further tweak it according to your needs, may be checking line contents too and most importantly this is very easy to disable and will work with any code.