2

Trying to use a swift script to run an executable in the system. I followed the second answer here, however I run into an error complaining that Foundation was not properly built:

The error:

/usr/lib/swift/CoreFoundation/CoreFoundation.h:25:10: note: while building module 'SwiftGlibc' imported from /usr/lib/swift/CoreFoundation/CoreFoundation.h:25:
#include <sys/types.h>
         ^

The code:

import Foundation

func execCommand(command: String, args: [String]) -> String {
    if !command.hasPrefix("/") {
        let commandFull = execCommand(command: "/usr/bin/which", args: [command]).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        return execCommand(command: commandFull, args: args)
    } else {
        let proc = Process()
        proc.launchPath = command
        proc.arguments = args
        let pipe = Pipe()
        proc.standardOutput = pipe
        proc.launch()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        return String(data: data, encoding: String.Encoding.utf8)!
    }
}

let commandOutput = executeCommand("/bin/echo", ["Hello, I am here!"])
println("Command output: \(commandOutput)")

I am running this using Sublime REPL in Linux (Archlinux). Questions:

  • All other small projects I made worked well, never found an error with Foundation as it is complaining here. Is my installation the problem?

  • Is there a simpler way of running an executable using Glibc?

lf_araujo
  • 1,991
  • 2
  • 16
  • 39

1 Answers1

0

Answering my own question. That seems to be a bug in Sublime REPL for swift, as running it in command line makes the code run without problems. Also, there are a few problems with the code that wasn't updated to Swift 3, below is the passing code. I would still like to find out a way of running executables in Swift using Glibc as well.

#! /usr/bin/swift

import Foundation

func execCommand(command: String, args: [String]) -> String {
    if !command.hasPrefix("/") {
        let commandFull = execCommand(command: "/usr/bin/which", args: [command]).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        return execCommand(command: commandFull, args: args)
    } else {
        let proc = Process()
        proc.launchPath = command
        proc.arguments = args
        let pipe = Pipe()
        proc.standardOutput = pipe
        proc.launch()
        let data = pipe.fileHandleForReading.readDataToEndOfFile()
        return String(data: data, encoding: String.Encoding.utf8)!
    }
}

let commandOutput = execCommand(command:"/bin/echo", args:["Hello, I am here!"])
print("Command output: \(commandOutput)")
lf_araujo
  • 1,991
  • 2
  • 16
  • 39