xcode 6 swift system()命令 [英] xcode 6 swift system() command

查看:120
本文介绍了xcode 6 swift system()命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

swift系统命令是否有很好的描述?例如,此代码

Is there a good description of swift system command? For example, this code

    let x = system("ls -l `which which`")
    println(x)

产生 -rwxr-xr-x 1根轮14496 Aug 30 04:29/usr/bin/which

produces -rwxr-xr-x 1 root wheel 14496 Aug 30 04:29 /usr/bin/which

0

我想将输出与返回代码

推荐答案

system()不是Swift命令,而是BSD库函数.您获得了文档 在终端窗口中使用"man system" :

system() is not a Swift command but a BSD library function. You get the documentation with "man system" in a Terminal Window:

system()函数将自变量命令传递给命令 解释器sh(1).通话过程 等待外壳程序完成命令执行,忽略SIGINT和SIGQUIT,并阻止SIGCHLD.

The system() function hands the argument command to the command interpreter sh(1). The calling process waits for the shell to finish executing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD.

"ls"命令的输出仅写入标准输出,而不写入任何 Swift变量.

The output of the "ls" command is just written to the standard output and not to any Swift variable.

如果需要更多控制,则必须使用Foundation框架中的NSTask. 这是一个简单的示例:

If you need more control then you have to use NSTask from the Foundation framework. Here is a simple example:

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "ls -l `which which`"]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = NSString(data: data, encoding: NSUTF8StringEncoding) {
    println(output)
}

task.waitUntilExit()
let status = task.terminationStatus
println(status)

此处需要通过外壳程序"/bin/sh -c命令..."执行命令,因为 "back tick"参数.通常,最好直接调用命令, 例如:

Executing the command via the shell "/bin/sh -c command ..." is necessary here because of the "back tick" argument. Generally, it is better to invoke the commands directly, for example:

task.launchPath = "/bin/ls"
task.arguments = ["-l", "/tmp"]

这篇关于xcode 6 swift system()命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆