How to clear the interpreter console?

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

    If it is on mac, then a simple cmd + k should do the trick.

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

    here something handy that is a little more cross-platform

    import os
    
    def cls():
        os.system('cls' if os.name=='nt' else 'clear')
    
    # now, to clear the screen
    cls()
    
    0 讨论(0)
  • 2020-11-21 18:44

    The OS command clear in Linux and cls in Windows outputs a "magic string" which you can just print. To get the string, execute the command with popen and save it in a variable for later use:

    from os import popen
    with popen('clear') as f:
        clear = f.read()
    
    print clear
    

    On my machine the string is '\x1b[H\x1b[2J'.

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

    How about this for a clear

    - os.system('cls')
    

    That is about as short as could be!

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

    EDIT: I've just read "windows", this is for linux users, sorry.


    In bash:

    #!/bin/bash
    
    while [ "0" == "0" ]; do
        clear
        $@
        while [ "$input" == "" ]; do
            read -p "Do you want to quit? (y/n): " -n 1 -e input
            if [ "$input" == "y" ]; then
                exit 1
            elif [ "$input" == "n" ]; then
                echo "Ok, keep working ;)"
            fi
        done
        input=""
    done
    

    Save it as "whatyouwant.sh", chmod +x it then run:

    ./whatyouwant.sh python
    

    or something other than python (idle, whatever). This will ask you if you actually want to exit, if not it rerun python (or the command you gave as parameter).

    This will clear all, the screen and all the variables/object/anything you created/imported in python.

    In python just type exit() when you want to exit.

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

    I'm not sure if Windows' "shell" supports this, but on Linux:

    print "\033[2J"

    https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes

    In my opinion calling cls with os is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.

    0 讨论(0)
提交回复
热议问题