Getting input from stdin in a Cocoa command line application subprocess

I have a command-line application A, and AI am doing an executable script B, to Bwait for input from stdin.

I wrote a demo, implementing it Ain Swift, using Foundation Processapi, finding that B, regardless of what is implemented in any language, it cannot get user input from stdin.

the code:

// `A` main.swift
import Foundation
let process = Process()
process.launchPath = PATH_TO_SCRIPT_B
process.launch()
process.waitUntilExit()

// `B`
#!/usr/bin/swift 
print("intpu something")
let input = readLine()
print("input: \(input)")

I did not set the input Processas according to the document

If this method is not used, standard input is inherited from the process that the receiver created.


UPDATE:

A - , Swift. swift package generate-xcodeproj Xcode. , , swift build xcodebuild , stdin B. , Xcode, command + R Xcode, . , Xcode, , , .

+4
1
func task() {
  print("input here")
  let x = input()
  print ("inputed:" + x)
}

func input() -> String {
  let keyboard = FileHandle.standardInput
  let inputData = keyboard.availableData
  let strData = String(data: inputData, encoding: .utf8)!

  let string = strData.trimmingCharacters(in: .newlines)
  return string
}

task()

,

+1

Source: https://habr.com/ru/post/1661806/


All Articles