【问题标题】:Why my arguments are being blocked when running a shell command?为什么在运行 shell 命令时我的参数被阻止?
【发布时间】:2020-09-23 23:44:56
【问题描述】:

我希望通过我在 MAC 中的 SWIFT 应用程序在命令行上运行命令。

var resString = "open \(app.getLocation()) --args 25 40"
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", resString]
task.launch()
print (resString)

当我在控制台上打印 resString 时,我得到以下内容

open [path to app on my local drive] --args 25 40

当我在命令行中复制粘贴时正常执行。但另一方面,应用程序已打开,但参数被忽略。

我也试过这个https://stackoverflow.com/a/53725745/12197482 仍然没有用,应用程序已启动但参数没有通过

编辑:这是最令人沮丧的最有趣的事情,我创建了一个包含命令的小脚本,其中包含

#! /bin/bash
open ./SimulatorDebug.app --args arg1 arg2

我再次从终端运行它,参数正确传递,没有问题。我尝试从我的应用程序运行,但同样的问题再次发生,应用程序运行播放但没有传递任何 ARGS,我觉得这很奇怪。

【问题讨论】:

  • 参数应该作为数组传递:task.arguments = ["-c", "open", app.getLocation(), "--args", "25", "40"]。如果应用是沙盒的,你无论如何都不能使用Process
  • @vadian,好吧,你是对的,当我删除沙箱时不知何故传递了参数,但我确实需要一个沙箱,因为我正在从本地服务器下载文件。我能做些什么解决方法?
  • 请阅读objc.io/issues/14-mac/sandbox-scripting。这是关于 AppleScript 但它与 shell 脚本的模式相同。

标签: swift macos shell macos-catalina


【解决方案1】:

尝试将/bin/sh 用作executableURL

task.executableURL = URL(fileURLWithPath: "/bin/sh")

应该可以的。

您可能还想尝试改用task.run(),并等待完成:

try task.run()
task.waitUntilExit()

我编写 System 是为了让这更容易。随意使用它或复制/粘贴代码: https://github.com/eneko/System/blob/master/Sources/System/System.swift#L107

更新了更多信息

由于您尝试打​​开一个macOS应用程序,因此无需使用shbash,您可以直接调用open

为了测试这一点,我在 Xcode 中编写了一个示例 macOS 应用程序,它所做的只是在屏幕上显示参数。然后,我继续从 macOS Playground 启动应用程序,如屏幕截图所示:

这是使用参数启动应用程序的代码:

let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/open")
process.arguments = [
    "/Applications/ArgumentTest/ArgumentTest.app",
    "-n",
    "--args",
    "Open",
    "From",
    "Playground"
]

try process.run()

-n 用于启动应用程序的实例,即使应用程序已经在运行。在您的情况下可能不需要。

希望这会有所帮助!

【讨论】:

  • 还是没有运气!该应用程序确实启动了,但没有传递任何参数!简而言之,我从终端执行的命令是“打开 /Users/user/Downloads/test.app --args 25 40”,在另一个应用程序上我成功记录了 args,但是在 SWIFT 中执行字面复制粘贴时应用程序启动但没有 args 的命令 task.arguments = ["-c", "open /Users/user/Downloads/test.app --args 25 40"]
  • 我几乎翻遍了所有论坛,关注了很多功能,它们都启动了.app文件但不注入任何args
  • 我也将系统包导入我的项目并尝试了,仍然没有运气!我认为这是与 SWIFT 相关的问题
  • 如何以root权限运行?
  • @john elemans 就像我提到的,如果不允许这些操作,它不会让应用程序运行并阻止参数
猜你喜欢
  • 2015-08-08
  • 1970-01-01
  • 2010-11-18
  • 2018-07-28
  • 1970-01-01
  • 2014-08-25
  • 2018-04-18
  • 2019-08-15
  • 1970-01-01
相关资源
最近更新 更多