How to clear the interpreter console?

后端 未结 30 2196
自闭症患者
自闭症患者 2020-11-21 18:15

Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff

相关标签:
30条回答
  • 2020-11-21 18:19

    Here are two nice ways of doing that:

    1.

    import os
    
    # Clear Windows command prompt.
    if (os.name in ('ce', 'nt', 'dos')):
        os.system('cls')
    
    # Clear the Linux terminal.
    elif ('posix' in os.name):
        os.system('clear')
    

    2.

    import os
    
    def clear():
        if os.name == 'posix':
            os.system('clear')
    
        elif os.name in ('ce', 'nt', 'dos'):
            os.system('cls')
    
    
    clear()
    
    0 讨论(0)
  • 2020-11-21 18:20

    I use iTerm and the native terminal app for Mac OS.

    I just press ⌘ + k

    0 讨论(0)
  • 2020-11-21 18:20

    The easiest way is to use os module

    >>> import os
    >>> clear = lambda: os.system('clear')
    >>> clear()
    
    0 讨论(0)
  • 2020-11-21 18:22

    This is the simplest thing you can do and it doesn't require any additional libraries. It will clear the screen and return >>> to the top left corner.

    print("\033[H\033[J")
    
    0 讨论(0)
  • 2020-11-21 18:22

    Here's the definitive solution that merges all other answers. Features:

    1. You can copy-paste the code into your shell or script.
    2. You can use it as you like:

      >>> clear()
      >>> -clear
      >>> clear  # <- but this will only work on a shell
      
    3. You can import it as a module:

      >>> from clear import clear
      >>> -clear
      
    4. You can call it as a script:

      $ python clear.py
      
    5. It is truly multiplatform; if it can't recognize your system
      (ce, nt, dos or posix) it will fall back to printing blank lines.


    You can download the [full] file here: https://gist.github.com/3130325
    Or if you are just looking for the code:

    class clear:
     def __call__(self):
      import os
      if os.name==('ce','nt','dos'): os.system('cls')
      elif os.name=='posix': os.system('clear')
      else: print('\n'*120)
     def __neg__(self): self()
     def __repr__(self):
      self();return ''
    
    clear=clear()
    
    0 讨论(0)
  • 2020-11-21 18:23

    for the mac user inside the python console type

    import os
    os.system('clear')
    

    for windows

    os.system('cls')
    
    0 讨论(0)
提交回复
热议问题