我如何 运行 来自 Mac 的 Spotlight 的 Python 脚本(而不是必须打开终端或 Pycharm)?

How Do I Run a Python Script from Mac's Spotlight (Instead of Having to Open Terminal or Pycharm)?

我使用的是 MacBook Pro 16"(装有 MacOS Catalina)。我想 运行 Python 直接通过 Spotlight 搜索脚本。我不想打开任何 IDE 或终端。我看到指示告诉我:

  1. 编写并保存我的 Python 代码,例如:print("Hello World"),在主文件夹 Users/Gory

    中保存为 hello.py
  2. 使用 TextEdit 创建文本文件并使用 .command 文件扩展名保存(例如:samplescript.command)。该文件应包含以下内容

    #!/usr/bin/env bash
    python3 /Users/Gory/hello.py
    
  3. 使上面创建的 shell 脚本 (samplescript.command) 由 运行ning 在终端中执行:

    chmod u+x samplescript.command
    

按照上面的步骤,我通过Spotlight搜索了samplescript.command,然后按回车。我希望在终端 window 上看到“Hello World”。相反,我收到以下消息:

MacBook-Pro:~ Gory$ /Users/Gory/samplescript.command ; exit;
/Users/Gory/samplescript.command: line 1: {rtf1ansiansicpg1252cocoartf2511: command not found
/Users/Gory/samplescript.command: line 2: syntax error near unexpected token `}'
/Users/Gory/samplescript.command: line 2: `\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

怎么了?

我是一名学习者,也遇到过类似的问题。 我的在 shebang 行中使用了额外的 space,我 运行 chmod 到完整的文件路径。

"#! /usr/bin/env bash"

你的问题

您的问题是由您的第二步引起的:

Create a text file using TextEdit and save it with .command file extension (e.g.: samplescript.command). The file should contain the following

默认情况下,TextEdit 使用 Rich Text 格式。

结果:您的 samplescript.command 文件不包含您期望的内容

#!/usr/bin/env bash
python3 /Users/Gory/hello.py 

但实际上

{\rtf1\ansi\ansicpg1252\cocoartf2513
\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0

\f0\fs24 \cf0 #!/usr/bin/env bash\
python3 /Users/Gory/hello.py}

此类内容不是有效的命令,然后在执行时导致观察到的错误:

line 1: {rtf1ansiansicpg1252cocoartf2513: command not found
line 2: syntax error near unexpected token `}'
line 2: `\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}'

如何解决?

如果您想使用 TextEdit,请在输入任何内容之前将格式从 Rich Text 更改为 Plain Text。

  1. 创建新文档
  2. 格式菜单 ➜ 制作纯文本
  3. 插入您的内容,保存

更好地修复:

不要使用 TextEdit 或任何其他类型的文本处理器应用程序编写代码(脚本),以便从一开始就避免此类问题。

无论如何,无论您使用什么编辑器,请仔细检查(脚本)文件内容是否确实是您期望的内容。