V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Shared
V2EX  ›  Swift

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

  •  1
     
  •   Shared ·
    vayn · Oct 17, 2016 · 6439 views
    This topic created in 3482 days ago, the information mentioned may be changed or developed.

    之前做了使用 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 新手,我就卡到这儿了……

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

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2699 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:08 · PVG 11:08 · LAX 20:08 · JFK 23:08
    ♥ Do have faith in what you're doing.