V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Shared
V2EX  ›  Swift

[Swift 3] 如何使用 Process 调用外部命令?

  •  1
     
  •   Shared ·
    vayn · 2016-10-17 15:14:14 +08:00 · 5472 次点击
    这是一个创建于 2719 天前的主题,其中的信息可能已经有所发展或是发生改变。

    之前做了使用 mpv 播放器播放 Acfun 视频的 acmpv,不过每次还需要复制网址再粘贴到终端调用相关命令,于是就想直接监控剪贴板,如果复制的是 Acfun 网址就直接调用 acmpv 播放。

    想好了就动手,监控剪贴板这块儿很快搞定,问题出在使用 Process (原 NSTask )调用外部命令上。

    先上代码(全部代码在 GitHub):

    let process = Process()
    
    let outpipe = Pipe()
    process.standardOutput = outpipe
    let errpipe = Pipe()
    process.standardError = errpipe
    
    process.launchPath = "/usr/local/bin/acmpv"
    process.arguments = ["-f=mp4", copiedString]
    process.launch()
    
    let outdata = outpipe.fileHandleForReading.availableData
    let outputString = String(data: outdata, encoding: String.Encoding.utf8) ?? ""
    NSLog("Ouput: %@", outputString)
    
    let errdata = errpipe.fileHandleForReading.availableData
    let errString = String(data: errdata, encoding: String.Encoding.utf8) ?? ""
    NSLog("Err: %@", errString)
    
    process.waitUntilExit()
    

    执行后并没有 mpv 弹出,而是在 console 输出:

    warning: the gestalt selector gestaltsystemversion is returning 10.9.0 instead
    of 10.12.0...
    

    在 Google 上搜索半天没有一条有用的,所以作为一个 Swift + Cocoa 新手,我就卡到这儿了……

    请教下各位高手,如何才能正确调用外部命令?

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5413 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 06:47 · PVG 14:47 · LAX 23:47 · JFK 02:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.