How to clear the interpreter console?

后端 未结 30 2722
自闭症患者
自闭症患者 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:42

    Although this is an older question, I thought I'd contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I'm on Windows at the moment, it's slightly biased that way, but could easily be slanted some other direction.

    Here's some articles I found that describe how to set environment variables on Windows:
        When to use sys.path.append and when modifying %PYTHONPATH% is enough
        How To Manage Environment Variables in Windows XP
        Configuring System and User Environment Variables
        How to Use Global System Environment Variables in Windows

    BTW, don't put quotes around the path to the file even if it has spaces in it.

    Anyway, here's my take on the code to put in (or add to your existing) Python startup script:

    # ==== pythonstartup.py ====
    
    # add something to clear the screen
    class cls(object):
        def __repr__(self):
            import os
            os.system('cls' if os.name == 'nt' else 'clear')
            return ''
    
    cls = cls()
    
    # ==== end pythonstartup.py ====
    

    BTW, you can also use @Triptych's __repr__ trick to change exit() into just exit (and ditto for its alias quit):

    class exit(object):
        exit = exit # original object
        def __repr__(self):
            self.exit() # call original
            return ''
    
    quit = exit = exit()
    

    Lastly, here's something else that changes the primary interpreter prompt from >>> to cwd+>>>:

    class Prompt:
        def __str__(self):
            import os
            return '%s >>> ' % os.getcwd()
    
    import sys
    sys.ps1 = Prompt()
    del sys
    del Prompt
    

提交回复
热议问题