简体   繁体   中英

How to start/run Python script automatically when file is downloaded (macOS)

I have written a script which uses watchdog to organize files into folders when they are downloaded, that is added to the Download folder. However, it only works if I manually start running the script and then add files to the Download folder. Is there a way that I can start the script automatically whenever the a file is downloaded without me having run the script in the terminal manually?

This is what the script looks like:

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()

UPDATE:

I have figured out that I will need to add it to the Automator. But get stuck at this step:

自动机

I don't know how to run the script using "/usr/bin/python" as shown in the image. I also tried "/bin/bash" with:

 cd Documents
 python organize_downloads.py

But this did not work either as it would give error on the imports.

I suspect your Run Shell Script automator step is mixed up a bit. It uses shell-commands like cd Folder and python script.py with the Python shell. I would decide for one of the shells, and then stick to it most explicitly. So you can:

either run it as regular Shell script with /bin/sh or /bin/bash :

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

Note: the path to python interpreter must be absolute (as shown above). Maybe also the path to your script must be absolute ( Documents relative to your user's home folder ~ as above).

or as Python script with /usr/bin/python :

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

See also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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