簡體   English   中英

在Cocoa命令行應用程序的子進程中從stdin獲取輸入

[英]Getting input from stdin in a Cocoa command-line app's sub process

我有一個命令行應用程序A ,在A我執行一個可執行腳本B ,在B我期待來自stdin的輸入。

我編寫了一個演示,使用FoundationProcess api在Swift中實現A ,發現B無論用什么語言實現都無法從stdin獲取用戶輸入。

碼:

// `A`'s 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)")

根據文檔,我沒有設置process的輸入:

如果未使用此方法,則標准輸入將從創建接收器的進程繼承。


更新:

A是使用Swift Package Manager創建的可執行包。 我使用swift package generate-xcodeproj來生成Xcode項目文件。 我確認如果我在shell中運行使用swift buildxcodebuild swift build的可執行文件,則從B獲取stdin的輸入問題就出現了。 但是如果我直接在Xcode中運行它,通過在Xcode中按下command + R ,那么它就可以了。 因此,如果我理解在shell和Xcode中運行可執行文件之間的區別,我可能會使一切正常。

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()

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM