【问题标题】:How to start/run Python script automatically when file is downloaded (macOS)下载文件时如何自动启动/运行 Python 脚本(macOS)
【发布时间】:2020-10-05 04:49:34
【问题描述】:

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

这就是脚本的样子:

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

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

【问题讨论】:

  • 将脚本添加到计算机启动?那么当一个文件被下载时它就会一直运行。
  • 您能否详细说明如何执行此操作?我似乎找不到太多关于它的信息,我发现的只是使用 Automator 可能有用。但是,Automator 似乎只运行 Apple 脚本或 Java 脚本,而不是 Python。 @艾伦胡佛
  • 我没有在 Mac 上做过。在 Windows 中,您将其添加到启动中。在 linux 中你把它放在 rc.d/init.d 中。谷歌搜索这些术语应该会给你一些想法。

标签: python bash macos python-watchdog


【解决方案1】:

我怀疑你的 Run Shell Script 自动化步骤有点搞混了。 它在 Python shell 中使用诸如 cd Folderpython script.py 之类的 shell 命令。我会决定选择其中一个贝壳,然后最明确地坚持下去。所以你可以:

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

/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

另见

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 2022-06-12
    • 2016-08-23
    相关资源
    最近更新 更多