How to clear the Terminal screen in Swift?

前端 未结 5 1731
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 19:02

I am writing a BASIC Interpreter for the Command Line in Swift 2, and I cannot find a way to implement the simple command, CLS (clear all text from the Terminal.) Should I s

相关标签:
5条回答
  • 2020-12-11 19:24

    This code makes a synchronous call to the built-in clear command. This won't cause problem with readLine() since it prints the escape sequence returned by clear using Swift's print() function

    var cls = Process()
    var out = Pipe()
    cls.launchPath = "/usr/bin/clear"
    cls.standardOutput = out
    cls.launch()
    cls.waitUntilExit()
            print (String(data: out.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8) ?? "")
    
    0 讨论(0)
  • 2020-12-11 19:31

    Use the built-in clear command either with system

    system("clear")
    

    or popen (ask Google)

    Alternatively, simulate the pressing of Ctrl+L using AppleScript via the command line:

    osascript -e 'tell app "terminal" to tell app "system events" to keystroke "l" using {control down}'
    

    EDIT: system is no longer available in newer verions of Swift. See Rudolf Adamkovič's answer.

    0 讨论(0)
  • 2020-12-11 19:34

    This answer applies to Swift 2.1 or earlier only

    To elaborate on Arc676's answer:

    The system command is imported into Swift via the Darwin module on Mac platforms (with other C APIs). On Linux, Glibc replaces Darwin for bridging low-level C APIs to Swift.

    import Glibc
    
    // ...
    
    system("clear")
    

    Or, if the system call is ambiguous, explicitly call Glibc's system (or Darwin on Mac platforms):

    import Glibc
    
    // ...
    
    Glibc.system("clear")
    
    0 讨论(0)
  • 2020-12-11 19:39

    This works for me in Swift 3.1

    var clearScreen = Process()
    clearScreen.launchPath = "/usr/bin/clear"
    clearScreen.arguments = []
    clearScreen.launch()
    clearScreen.waitUntilExit()
    

    You can create a function with a callback like this

    func clearScreen(completion:@escaping (Bool) -> () ) {
            let clearScreen = Process()
            clearScreen.launchPath = "/usr/bin/clear"
            clearScreen.arguments = []
            clearScreen.terminationHandler = { task in completion(true) }
            clearScreen.launch()
            clearScreen.waitUntilExit()
    }
    
    0 讨论(0)
  • 2020-12-11 19:40

    You can use the following ANSI sequence:

    print("\u{001B}[2J")
    

    ... where \u{001B} is ESCAPE and [2J is clear screen.

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