Home > Mobile >  Collect python output in Swift
Collect python output in Swift

Time:01-24

is it possible to store the output of a .py file in a swift variable? In my xcode project I have put a python script. I run this script using this code

class ViewController: NSViewController {
    var pathForFile = Bundle.main.path(forResource: "eject", ofType: "py")
    let path = "/usr/bin/python/"
        
    override func viewDidLoad() {
            
            let arguments = [pathForFile]
            let task = Process.launchedProcess(launchPath: path, arguments: arguments as! [String])
            task.waitUntilExit()
            super.viewDidLoad()

        }
}

If I put print(x) in the python file, once executed I can see the x value on the output window of xcode.
I also tried to put return x in the main function and then tried to set let y = task.waitUntilExit() in the swift file, but the only thing I get is an empty variable

I don't know much about swift, so please forgive my lack of knowledge. Thanks in advance!

CodePudding user response:

Solution

As explained in this page
https://www.hackingwithswift.com/example-code/system/how-to-run-an-external-program-using-process
and shown in the answer suggested by Willeke, you can use Pipe() to do that.
I changed the code as shown below.

override func viewDidLoad() {
    super.viewDidLoad()
    let task = Process()
    task.executableURL = URL(fileURLWithPath: "/usr/bin/python")
    let filename = Bundle.main.path(forResource: "eject", ofType: "py")
    task.arguments = [filename!]
    let outputPipe = Pipe()
    task.standardOutput = outputPipe
    
       do{
           try task.run()
       } catch {
           print("error")
       }
    
    let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(decoding: outputData, as: UTF8.self)
    print(output)
    
   }

Be sure to put this

let outputPipe = Pipe()
task.standardOutput = outputPipe

before the task.run() command and this

let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let output = String(decoding: outputData, as: UTF8.self)
print(output)

after it.

  •  Tags:  
  • Related