![](/img/trans.png)
[英]macOS : programmatic check if process runs as a launchDaemon or launchAgent or from command-line
[英]Getting input from stdin in a Cocoa command-line app's sub process
我有一個命令行應用程序A
,在A
我執行一個可執行腳本B
,在B
我期待來自stdin的輸入。
我編寫了一個演示,使用Foundation
的Process
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 build
或xcodebuild
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.