Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an external command in Swift

Tags:

swift

exec

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

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

like image 577
RyanM Avatar asked Jun 20 '14 22:06

RyanM


People also ask

What is Task Swift?

Tasks in Swift are part of the concurrency framework introduced at WWDC 2021. A task allows us to create a concurrent environment from a non-concurrent method, calling methods using async/await. When working with tasks for the first time, you might recognize familiarities between dispatch queues and tasks.


1 Answers

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()
like image 150
Connor Avatar answered Sep 21 '22 02:09

Connor