Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift 5中正确执行shell命令_Swift_Bash_Shell_Process_Nstask - Fatal编程技术网

在Swift 5中正确执行shell命令

在Swift 5中正确执行shell命令,swift,bash,shell,process,nstask,Swift,Bash,Shell,Process,Nstask,我是swift的新手,尝试在互联网上学习几种不同的教程,让我的应用程序运行终端程序 我有一个复选框,应该启用(通过终端命令)充电蜂鸣音(当然,取消选中时将其关闭) 编辑: 更新的代码,仍然不起作用: @discardableResult func shell(_ command: String) -> String { let task = Process() task.launchPath = "/usr/bin/" task.arguments = ["-c",

我是swift的新手,尝试在互联网上学习几种不同的教程,让我的应用程序运行终端程序

我有一个复选框,应该启用(通过终端命令)充电蜂鸣音(当然,取消选中时将其关闭)

编辑: 更新的代码,仍然不起作用:

@discardableResult func shell(_ command: String) -> String {
    let task = Process()
    task.launchPath = "/usr/bin/"
    task.arguments = ["-c", command]

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

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String

    return output
}


@IBAction func SoundBox(_ sender: NSButton) {

    if(SoundBox.state == NSControl.StateValue.on){

        self.helloLabel.stringValue = "It's On!"

        shell("say hello")
        //shell("defaults write com.apple.PowerChime ChimeOnAllHardware -bool true; open /System/Library/CoreServices/PowerChime.app &")

    }
    else if(SoundBox.state == NSControl.StateValue.off){
        self.helloLabel.stringValue = "It's off!"

        shell("say hello")
        //shell("defaults write com.apple.PowerChime ChimeOnAllHardware -bool false; killall PowerChime")


    }
新控制台输出:

  2019-04-12 16:44:54.792282+0200 TerminApp[2985:45592] [General] Couldn't posix_spawn: error 13
2019-04-12 16:44:54.795254+0200 TerminApp[2985:45592] [General] (
    0   CoreFoundation                      0x00007fff42444e45 __exceptionPreprocess + 256
    1   libobjc.A.dylib                     0x00007fff6d07c3c6 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff42444c77 +[NSException raise:format:] + 193
    3   Foundation                          0x00007fff446495e9 -[NSConcreteTask launchWithDictionary:error:] + 4437
    4   TerminApp                           0x000000010000299b $s9TerminApp14ViewControllerC5shellyS2SF + 635
    5   TerminApp                           0x000000010000349e $s9TerminApp14ViewControllerC8SoundBoxyySo8NSButtonCF + 1438
    6   TerminApp                           0x000000010000360c $s9TerminApp14ViewControllerC8SoundBoxyySo8NSButtonCFTo + 60
    7   AppKit                              0x00007fff3fcf8e80 -[NSApplication(NSResponder) sendAction:to:from:] + 312
    8   AppKit                              0x00007fff3fd63196 -[NSControl sendAction:to:] + 86
    9   AppKit                              0x00007fff3fd630c8 __26-[NSCell _sendActionFrom:]_block_invoke + 136
    10  AppKit                              0x00007fff3fd62fca -[NSCell _sendActionFrom:] + 178
    11  AppKit                              0x00007fff3fd8fd4f -[NSButtonCell _sendActionFrom:] + 96
    12  AppKit                              0x00007fff3fd618e5 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2375
    13  AppKit                              0x00007fff3fd8faa0 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 698
    14  AppKit                              0x00007fff3fd60322 -[NSControl mouseDown:] + 791
    15  AppKit                              0x00007fff3fc3c16f -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] + 5724
    16  AppKit                              0x00007fff3fb729de -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 2295
    17  AppKit                              0x00007fff3fb71e9f -[NSWindow(NSEventRouting) sendEvent:] + 478
    18  AppKit                              0x00007fff3fa116c3 -[NSApplication(NSEvent) sendEvent:] + 331
    19  AppKit                              0x00007fff3f9ffee8 -[NSApplication run] + 755
    20  AppKit                              0x00007fff3f9ef3f0 NSApplicationMain + 777
    21  TerminApp                           0x000000010000475d main + 13
    22  libdyld.dylib                       0x00007fff6e8a13d5 start + 1
)

这就是我在应用程序中启动ffmpeg的方法。(
ffmpegTask
是一个
进程!
实例,声明为实例属性,
prefs.input\u uri
是一个字符串,来自用户输入-它是RTSP流的uri)。希望这有帮助(“临时文件”的内容来自):

据码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码码############################*/ /** 这将启动ffmpeg任务。 -返回:如果任务成功启动,则返回True。 */ func startFFMpeg()->Bool{ ffmpegTask=进程() //首先,我们要确保我们有一个进程,它是一个条件初始化。 如果让ffmpegTask=ffmpegTask{ //接下来,为流文件设置tempdir。 如果让tmp=try?临时文件(creatingTempDirectoryForFilename:“stream.m3u8”){ OutputMPFile=tmp //从包中获取可执行路径。我们在应用程序中有ffmpeg的副本。 如果var executablePath=(Bundle.main.executablePath作为NSString?).deletingLastPathComponent{ 可执行路径+=“/ffmpeg” ffmpegTask.launchPath=可执行路径 ffmpegTask.arguments=[ “-i”,prefs.input_uri, “-sc_阈值”,“0”, “-f”、“hls”, “-hls_标志”、“删除_段”, “-hls_时间”,“4”, OutputMPFile?.fileURL.path??“” ] #如果调试 如果让args=ffmpegTask.arguments,则1
沙箱可能是一个问题,这取决于您呼叫的位置。ffmpeg无论如何都不喜欢沙盒,但我仍然将为我的应用程序构建的变体嵌入到与主应用程序可执行文件相同的目录中。

我的第一个猜测是,这是因为您将参数作为数组的一个元素传递,所以swift将其视为单个参数。不过我不是swift专家。尝试分离您的命令,看看它是否有效您是否尝试过将
open/System/Library/CoreServices/PowerChime.app&
作为一个单独的命令运行,而不是作为
defaults
的参数的一部分运行?如果您想直接调用bash命令而不像以前那样使用参数分离,创建一个像中这样的自定义函数可能是一个解决方案。我很接近了,但仍然有一些失败。如果您在终端中键入
say hello
,它会工作吗?你是说
shell(“echo
打招呼
?另外,可能需要执行
[“-l”,“-c”,命令]
/* ################################################################## */
/**
 This starts the ffmpeg task.

 - returns: True, if the task launched successfully.
 */
func startFFMpeg() -> Bool {
    ffmpegTask = Process()

    // First, we make sure that we got a Process. It's a conditional init.
    if let ffmpegTask = ffmpegTask {
        // Next, set up a tempdir for the stream files.
        if let tmp = try? TemporaryFile(creatingTempDirectoryForFilename: "stream.m3u8") {
            outputTmpFile = tmp

            // Fetch the executable path from the bundle. We have our copy of ffmpeg in there with the app.
            if var executablePath = (Bundle.main.executablePath as NSString?)?.deletingLastPathComponent {
                executablePath += "/ffmpeg"
                ffmpegTask.launchPath = executablePath
                ffmpegTask.arguments = [
                    "-i", prefs.input_uri,
                    "-sc_threshold", "0",
                    "-f", "hls",
                    "-hls_flags", "delete_segments",
                    "-hls_time", "4",
                    outputTmpFile?.fileURL.path ?? ""
                ]

                #if DEBUG
                    if let args = ffmpegTask.arguments, 1 < args.count {
                        let path = ([executablePath] + args).joined(separator: " ")
                            print("\n----\n\(String(describing: path))")
                    }
                #endif

                // Launch the task
                ffmpegTask.launch()

                #if DEBUG
                    print("\n----\n")
                #endif

                return ffmpegTask.isRunning
            }
        }
    }

    return false
}