首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >允许程序从stdin或Swift中读取参数

允许程序从stdin或Swift中读取参数
EN

Stack Overflow用户
提问于 2019-11-26 22:14:29
回答 2查看 606关注 0票数 3

我想写一个Swift程序

  • 接受标准输入中的单个参数或管道数据,如果两者都缺少,则打印

假设代码包含在main.swift中,我们有四种情况:

  1. swift main.swift应该输出“请提供一些input"
  2. swift main.swift argument应该输出"argument"
  3. echo | swift main.swift应该输出”请提供一些input"
  4. echo argument | swift main.swift应该输出“参数”

在复合echo argument1 | swift main.swift argument2的情况下,argument2优先。

令人满意的1-3很简单:

代码语言:javascript
复制
import Foundation

var input: String? = nil

if CommandLine.arguments.count > 1 {
    input = CommandLine.arguments[1]
}

guard let input = input else {
    print("Please provide some input")
    exit(0)
}

print(input)

但是,echo argument | swift main.swift显然打印了使用消息,因为没有参数。添加一些代码,

代码语言:javascript
复制
import Foundation

var input: String? = nil

if CommandLine.arguments.count > 1 {
    input = CommandLine.arguments[1]
} else {
    while let line = readLine() {
        if input == nil {
            if line.isEmpty { break }
            input = line
        } else {
            input! += "\n" + line
        }
    }
}

guard let input = input else {
    print("Please provide some input")
    exit(0)
}

print(input)

现在案例2-4按预期工作,但案例1是有问题的。readLine()导致执行暂停,等待输入。如果您在没有输入的情况下按“返回”,则返回正确的消息,但我希望避免手动输入空行的必要性。

如何从stdin读取启用读取,而在stdin为空且没有参数时不会导致暂停?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-27 00:03:53

我认为问题在于,readLine()只会等待某种输入,即使它只是使用ctrl-d来发送行尾。对于您的使用,是否可以添加一个参数来告诉程序应该等待输入?否则,它就可以假设它不应该等待任何东西?

例如:

代码语言:javascript
复制
import Foundation

func readInput () -> String? {
    var input:String?

    while let line = readLine() {
        if input == nil {
            if line.isEmpty { break }
            input = line
        } else {
            input! += "\n" + line
        }
    }

    return input
}

var input: String? = nil

if CommandLine.arguments.count > 1 {
    input = CommandLine.arguments[1]

    if (input == "-i") {
        input = readInput()
    }
}

guard let input = input else {
    print("Please provide some input")
    exit(0)
}

print("input: \(input)")

然后您将得到如下所示的使用和输出:

票数 3
EN

Stack Overflow用户

发布于 2019-11-27 01:28:19

乔希·布勒( Josh Buhler )提供了一个缺失的部分--传递一个旗子,以便读取stdin。这是我的最后一个简化的完整解决方案。

代码语言:javascript
复制
import Foundation

guard CommandLine.arguments.count > 1 else {
    print("Please provide an argument, or pass - to read stdin")
    exit(0)
}

var input = CommandLine.arguments[1]

if input == "-" {
    input = AnyIterator { readLine() }.joined(separator: "\n")
}

// do something with input
print(input)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59060151

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档