繁体   English   中英

如何通过第一个命令行参数从 spotlight on macOS 执行 shell 脚本?

[英]How can execute a shell script from spotlight on macOS passing a first command line argument?

我编写了一个 python 程序,它需要第一个命令行参数才能从终端运行。 该程序可用于在使用特定关键字运行时将文本复制到剪贴板。

~ python3 mclip.py 'agree'

这个用例只是一个练习,以了解我如何在 macOS 上运行批处理文件(或 macOS 术语中的 shell 脚本)。

我创建了以下 shell 脚本并将其保存为mclip.command

#!/usr/bin/env bash
python3 /Users/Andrea_5K/mclip.py

我的想法是从聚光灯输入 window 执行我的 shell 脚本,传递参数“同意”。 我怎样才能做到这一点?

在 windows 上,批处理文件看起来像这样 ( mclip.bat ):

@py.exe C:\path_to_my_file\mclip.py %*
@pause

我可以按 WIN-R 并键入mclip *argument*来运行程序。 但是我怎样才能在 Mac 上做同样的事情呢? 我无法在 Spotlight 中键入mclip agree ,这不像在 WIN-R 中那样工作。

#! python3
# mclip.py - A multi-clipboard program.

TEXT = {
    'agree': """Yes, I agree. That sounds fine to me.""",
    'busy': """Sorry, can we do this later this week or next week?""",
    'upsell': """Would you consider making this a monthly donation?""",
}

import sys, pyperclip
if len(sys.argv) < 2:
    print('Usage: python mclip.py [keyphrase] - copy phrase text')
    sys.exit()

keyphrase = sys.argv[1] # first command line arg is the keyphrase

if keyphrase in TEXT:
    pyperclip.copy(TEXT[keyphrase])
    print('Text for ' + keyphrase + ' copied to clipboard.')
else:
    print('There is no text for ' + keyphrase)

我可以让 Spotlight 运行一个脚本:

  • 为您提供一个包含三个选项的对话框,以及
  • 然后运行您的 Python 脚本传递所选选项

但我无法让 Spotlight 直接将选项传递给 Python 脚本。 如果这有帮助,这里是如何做到的。


启动Script Editor并输入以下代码,将其保存为名为mclipapp

set theArg to choose from list {"Agree", "Busy", "Upsell"} with title "Chooser Dialog" with prompt "Choose option"

tell application "Terminal"
    do shell script "/Users/YOURNAME/mclip.py " & theArg
end tell

请注意,在顶部添加on run argv仍然不会让您在 Spotlight 中添加任何 arguments - 它似乎不想传递您在 Spotlight 对话框中键入的任何 arguments。


现在编写一个名为$HOME/mclip.py的 Python 脚本:

#!/usr/bin/env python3

import os, sys

 # Just write the received parameter into a text file on the Desktop to show how it works
file = os.path.expanduser("~/Desktop/result.txt")
with open(file, 'w') as f:
   f.write(sys.argv[1])

并使其可执行(只需要一次):

chmod +x $HOME/mclip.py

如果您现在使用Spotlight运行mclip ,它将弹出一个对话框,如下所示:

在此处输入图像描述

您可能必须在首次运行时回答安全问题 - 取决于您的 macOS 版本。

请注意,如果您的所有 Python 脚本确实是将一些文本复制到剪贴板上,则可以在上面的 Applescript 中不使用 Python 来执行此操作:

set the clipboard to "Some funky text"

假设 shell 脚本(mapIt.command)是:

#!/usr/bin/env bash
python3 /path/to/my/pythonScript.py $@ 

$@ 被解释为命令行 arguments 的列表。

我可以像这样在 MacOS 终端中运行 shell 脚本:

sh mapIt.command Streetname Number City

命令行 arguments Streetname Number City被转发到 python 脚本。

只是一个细节:python 区分大小写。 所以,如果字典的键是小写的,那么 apple 脚本中的列表值应该小写为 `:D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM