【问题标题】:how to pass command-line arguments to a program run with the open command?如何将命令行参数传递给使用 open 命令运行的程序?
【发布时间】:2018-06-22 11:46:38
【问题描述】:

有没有办法将参数传递给正在运行的程序:

open -a /Applications/Utilities/Terminal.app ~/my_executable

我试过了:

open -a /Applications/Utilities/Terminal.app ~/my_executable arg1 arg2

但这被解释为告诉终端打开~/my_executable ~/arg1 ~/arg2.

我试过了:

open -a /Applications/Utilities/Terminal.app '~/my_executable arg1 arg2'

但它会拾取 arg1 和 arg2,就好像它们是路径的一部分而不是参数一样。

我试过了:

open -a /Applications/Utilities/Terminal.app ~/my_executable | xargs arg1 arg2

我也试过了:

open -a /Applications/Utilities/Terminal.app ~/my_executable --args arg1 arg2

但是有了那个标志,args 被传递到终端。

注意

我只允许将参数更改为 Terminal.app([ ] 内的部分):

open -a /Applications/Utilities/Terminal.app [~/my_executable arg1 arg2]

【问题讨论】:

  • 是否有理由不使用open 命令直接运行可执行文件?
  • 是的,因为这是 Xcode 使用的命令:/Trying to pass arguments to a program that uses ncurses(因此必须在终端窗口中调试)。
  • 你尝试将 --args 放在你的 ecexutable 前面:open -a /Applications/Utilities/Terminal.app --args ~/my_executable arg1 arg2 ?
  • 这也不行,@chown。您可以通过打开终端并输入此命令自己尝试。 open -n -a /Applications/Utilities/Terminal.app --args ~/my_executable arg1 arg2

标签: macos bash


【解决方案1】:

可能最简单的方法是创建一个临时的 shell 脚本,例如

$ echo "~/my_executable arg1 arg2" > /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; rm /tmp/tmp.sh

【讨论】:

  • 那么让终端运行一个shell脚本来启动带有参数的可执行文件?这会起作用,不幸的是它必须创建和管理一个额外的 shell 脚本才能这样做。
  • 是的,很遗憾,我看不到更优雅的方式 - 这似乎是一个不容易解决的限制。
  • 另外,我必须在 rm /tmp/tmp.sh 之前添加 sleep 2 命令,因为 rm 命令运行得太快了。所以我的最终脚本是这样的:$ echo "~/my_executable arg1 arg2" > /tmp/tmp.sh ; chmod +x /tmp/tmp.sh ; open -a Terminal /tmp/tmp.sh ; sleep 2 ; rm /tmp/tmp.sh
【解决方案2】:

编辑:保留下面的原始答案,因为有些人似乎觉得它很有用,但请记住,这并不能真正回答 OP 的问题,这是为了将参数传递给打开的应用程序“打开”不是用“打开”打开的 Terminal.app 打开的应用程序。

您可以通过不带参数运行 open 来找到答案:

% open Usage: open [-e] [-t] [-f] [-W] [-R] [-n] [-g] [-h] [-b <bundle identifier>] [-a <application>] [filenames] [--args arguments]

[...]

--args All remaining arguments are passed in argv to the application's main() function instead of opened.

[...]

你可以看到有一个选项--args你可以这样使用它:

open ./Untitled.app --args arg1 arg2 arg3

我在 el Capitan (10.11.3) 上对其进行了测试,所以我不知道该选项是否存在于早期版本中。

【讨论】:

  • 这在您直接打开应用程序时有效,但 OP 试图让终端运行带参数的命令行可执行文件。
  • 由于某种原因,--args 无法在我的 macOS Catalina 10.15.7 机器上运行。终端应用程序打开脚本文件,但没有参数传递给脚本文件。
  • 恐怕我不应该得到所有这些支持,因为我并没有真正理解这个问题。尝试查看接受的答案。不幸的是,我认为没有其他方法可以做到这一点,除非有人添加更多关于为什么需要这样做的上下文(即问题假设 open 命令是原始未说明问题的唯一可能解决方案,其中似乎与在 xcode 中调试 cli 工具有关...)。
【解决方案3】:

是的,我知道。需要管理另一个脚本。 但想法不同。您不是在终端上工作,而是在脚本编辑器上工作。 (不是 bash 脚本,而是 AppleScript'ing)

property testScript : "/tmp/sh.sh"

set input to display dialog "args?" default answer ""
log input
tell application "Terminal"
    activate
    do script testScript & " " & text returned of input
end tell

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-12
    • 2011-05-20
    相关资源
    最近更新 更多