首页 > 解决方案 > 下载文件时如何自动启动/运行 Python 脚本(macOS)

问题描述

我编写了一个脚本,该脚本在下载文件时使用看门狗将文件组织到文件夹中,并将其添加到下载文件夹中。但是,它仅在我手动开始运行脚本然后将文件添加到下载文件夹时才有效。有没有一种方法可以在下载文件时自动启动脚本,而无需在终端中手动运行脚本?

这是脚本的样子:

from watchdog.observers import Observer
import time
from watchdog.events import FileSystemEventHandler
import os
import json

class HandleDownloads(FileSystemEventHandler):
    #observer.schedule runs on_modified()
    def on_modified(self, event):
        try:
            for filename in os.listdir(folder_to_track):
                src= folder_to_track + "/" + filename
                if ("U10" in filename):
                    new_destination = "/Users/user1/Documents/Studies/DDDC91" + "/" + filename
                    os.rename(src, new_destination)
        except:
            pass



folder_to_track = "/Users/user1/Downloads"

event_handler = HandleDownloads()
observer = Observer()
observer.schedule(event_handler, folder_to_track, recursive = True)
observer.start()

try:
    while True:
        time.sleep(10)
except KeyboardInterrupt:
    observer.stop()

更新:

我发现我需要将它添加到 Automator 中。但是卡在这一步:

自动机

如图所示,我不知道如何使用“/usr/bin/python”运行脚本。我还尝试了“/bin/bash”:

 cd Documents
 python organize_downloads.py

但这也不起作用,因为它会在导入时出错。

标签: pythonbashmacospython-watchdog

解决方案


我怀疑您的Run Shell Script automator 步骤有点混乱。它使用与 Python shell 类似的 shellcd Folder命令python script.py。我会决定选择其中一个贝壳,然后最明确地坚持下去。这样你就可以:

/bin/sh使用或将其作为常规 Shell 脚本运行/bin/bash

/Library/Frameworks/Python.framework/Versions/Current/bin/python ~/Documents/organize_downloads.py

注意:python解释器的路径必须是绝对路径(如上图)。也许您的脚本的路径也必须是绝对的(Documents相对于您的用户的主文件夹~,如上所述)。

或作为 Python 脚本/usr/bin/python

# contents of your script file pasted directly here as python code

也可以看看


推荐阅读