logo

Com esborrar la pantalla a Python?

La majoria de les vegades, mentre treballem amb l'intèrpret d'ordres/terminal interactiu de Python (no una consola), acabem amb una sortida desordenada i volem esborrar la pantalla per algun motiu. En un shell/terminal interactiu, simplement podem utilitzar

ctrl+l>

Però, què passa si volem esborrar la pantalla mentre executem un script Python? Malauradament, no hi ha cap paraula clau integrada ni funció o mètode per esborrar la pantalla. Per tant, ho fem pel nostre compte.



Esborrar la pantalla del sistema operatiu Windows

Mètode 1: esborra la pantalla a Python amb cls

Simplement podeu esborrar la pantalla a Windows.

Python 3



administrador de powershell






import> os> # Clearing the Screen> os.system(>'cls'>)>

>

>

forma normal de greibach

Exemple 2: esborra la pantalla a Python amb clear

També podeu importar només els sistemes operatius en comptes de des del sistema d'importació OS però amb això, has de canviar de sistema ('clar') a sistema os (‘clar’).

Python 3




# 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()>

>

>

Exemple 3: esborra la pantalla a Python mitjançant la trucada

Una altra manera d'aconseguir-ho és utilitzar el mòdul de subprocés .

Python 3

eliminar el primer caràcter excel




sql per ordre aleatori
# 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()>

>

>

Esborrar la pantalla del sistema operatiu Linux

En aquest exemple, hem utilitzat el mòdul de temps i mòdul os per esborrar la pantalla al sistema operatiu Linux.

Python 3




import> os> from> time>import> sleep> # some text> print>(>'a'>)> print>(>'b'>)> print>(>'c'>)> print>(>'d'>)> print>(>'e'>)> print>(>'Screen will now be cleared in 5 Seconds'>)> # Waiting for 5 seconds to clear the screen> sleep(>5>)> # Clearing the Screen> os.system(>'clear'>)>

>

>

llista d'inicialització de python