python - 下载文件时如何自动启动/运行 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
但这也不起作用,因为它会在导入时出错。
解决方案
我怀疑您的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
也可以看看
推荐阅读
- http - 从 HTTP 中的 Get/Post 请求返回 jsession id(使用的语言 - vbscript)
- class - 如何使快捷方式/绑定到类内的结构?(斯威夫特用户界面)
- flutter - 为什么flutter文件夹有错误
- r - 如何让我的代码仅感染图像上 50% 的受感染人群(红色方块)。图像必须并排
- polymer - 版本冲突 - 未捕获的 DOMException,名称“mwc-icon”已用于此注册表。自定义组件
- java - 无法访问的语句错误;在问题点之前没有无限循环或返回语句
- amazon-web-services - 何时通过重驱动策略将 SQS 消息发送到死信队列?
- elasticsearch - 弹性搜索中的突出显示未在输出中提供任何突出显示字段
- mysql - 带有位置消息的 MySQL 创建表错误
- java - Eclipse 提案缺少方法