大多数情况下,在使用python交互式shell/terminal(而不是控制台)时,我们最终会得到一个混乱的输出,出于某种原因希望清除屏幕。 在交互式外壳/终端中,我们可以简单地使用
null
ctrl+l
但是,如果我们想在运行python脚本时清除屏幕,该怎么办。 不幸的是,没有内置的关键字或函数/方法来清除屏幕。所以,我们自己做。
我们可以使用ANSI转义序列,但它们不可移植,可能无法产生所需的输出。
print(chr(27)+'[2j')print(' 33c')print('x1bc')
下面是我们在脚本中要做的:
- 从操作系统导入系统。
- 定义一个函数。
- 以Linux中的“clear”和Windows中的“cls”作为参数进行系统调用。
- 将返回的值存储在下划线或任何您想要的变量中(使用下划线是因为python shell总是将其最后的输出存储在下划线中)。
- 调用我们定义的函数。
# import only system from os from os import system, name # import sleep to show output for some time period from time import sleep # define our clear function def clear(): # for windows if name = = 'nt' : _ = system( 'cls' ) # for mac and linux(here, os.name is 'posix') else : _ = system( 'clear' ) # print out some text print ( 'hello geeks' * 10 ) # sleep for 2 seconds after printing output sleep( 2 ) # now call function we defined above clear() |
注意:您也只能“导入操作系统”而不是“从操作系统导入系统”,但这样,您必须将系统(“清除”)更改为操作系统。系统(“清除”)。
实现这一点的另一种方法是使用子流程模块。
# import call method from subprocess module from subprocess import call # import sleep to show output for some time period from time import sleep # define clear function def clear(): # check and make call for specific operating system _ = call( 'clear' if os.name = = 'posix' else 'cls' ) print ( 'hello geeks' * 10 ) # sleep for 2 seconds after printing output sleep( 2 ) # now call function we defined above clear() |
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END