Calling an external command in Swift

前端 未结 1 1656
离开以前
离开以前 2021-02-08 02:31

How can I call an external command (launch a subprocess) from a Swift script?

Perhaps something like call([\"ls\", \"-l\"]) in Python.

1条回答
  •  醉梦人生
    2021-02-08 03:26

    You can still use NSTask in Swift. Your example would be something like this.

    let task = NSTask()
    task.launchPath = "/bin/ls"
    task.arguments = ["-l"]
    task.launch()
    

    Swift 3+, macOS 10.13+

    let task = Process()
    task.executableURL = URL(fileURLWithPath: "/bin/ls")
    task.arguments = ["-l"]
    task.run()
    

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