36
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【OSX】【swift】コマンドの実行

Posted at

OS X 向けの簡単なGUIアプリを作り、ターミナルで実行していることをできれば
便利じゃないかなと思いまして。
(XcodeでiOSのように、IBActionから処理の指定ができたりするので)

まずはコマンドの実行について

##実行と引数の指定


        var  cmd:String = "/usr/bin/killall"
        var task:NSTask = NSTask()
        task.launchPath = cmd;
        //配列
        task.arguments  = ["Finder"]
        task.launch()

##標準出力の取得


        var  cmd:String = "/bin/echo"
        var task:NSTask = NSTask()
        task.launchPath = cmd;
        task.arguments  = ["hoge","hogehoge","hogehogehoge"]
        var pipe:NSPipe = NSPipe()
        task.standardOutput = pipe
        task.launch()
        var output:NSData = pipe.fileHandleForReading.readDataToEndOfFile()
        var outputStr:NSString = NSString(data:output,encoding:NSUTF8StringEncoding)!
        println(outputStr)

##対話型の場合の出力



        var  cmd:String = "/usr/bin/top"
        task = NSTask()
        task.launchPath = cmd;
        pipe = NSPipe()
        task.arguments = ["-s", "1", "-l", "3600", "-stats", "pid,cpu,time,command"];
        task.standardOutput = pipe
        task.launch()
        
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "notificationReadedData:",
            name:NSFileHandleReadCompletionNotification, object: nil)
        pipe.fileHandleForReading.readInBackgroundAndNotify()


NSNotificationCenterで通知を受け取る形にし、
(taskとpipeはメンバ変数にしています)

    func notificationReadedData(notification:NSNotification)
    {
        var output:NSData = notification.userInfo![NSFileHandleNotificationDataItem] as NSData;
        var outputStr:NSString = NSString(data:output,encoding:NSUTF8StringEncoding)!
        println(outputStr)
        if task.running {
            pipe.fileHandleForReading.readInBackgroundAndNotify()
        } else {
            NSNotificationCenter.defaultCenter().removeObserver(self,
                name:NSFileHandleReadCompletionNotification, object: nil)
        }
        
    }

なお、コマンドの停止は


task.terminate()


top時についての引数指定については以下を参考にさせていただきました
参考URL:http://stackoverflow.com/questions/3557594/nstask-to-call-command-top-getting-error

36
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?