如何实现Python程序在下载文件时自动运行?
Absolutely feasible! This is a super common automation task, and there are two reliable ways to make your Python script kick off automatically whenever Chrome finishes downloading a file (like images). Let’s break down each approach so you can pick what works best for you:
Method 1: Monitor the Chrome Download Folder (Simple & Universal)
The easiest way is to watch your Chrome download directory for new files. When a new image (or any file) finishes downloading, your script detects the change and runs your task. We’ll use the watchdog library for this—it’s built exactly for folder monitoring.
Steps to Implement:
- Install the
watchdoglibrary first:pip install watchdog - Write the monitoring script. Here’s a basic example that triggers when a new image is added to your downloads folder:
import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import os # Replace this with your Chrome download path DOWNLOAD_FOLDER = "C:/Users/YourName/Downloads" # Windows # DOWNLOAD_FOLDER = "/Users/YourName/Downloads" # macOS # DOWNLOAD_FOLDER = "/home/YourName/Downloads" # Linux class DownloadHandler(FileSystemEventHandler): def on_created(self, event): # Skip directories, only process files if not event.is_directory: file_path = event.src_path # Check if it's an image file (adjust extensions as needed) if file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')): print(f"New image detected: {file_path}") # Add your custom task here—e.g., resize, organize, upload # your_task_function(file_path) if __name__ == "__main__": event_handler = DownloadHandler() observer = Observer() observer.schedule(event_handler, DOWNLOAD_FOLDER, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() - Set Chrome to download files to this monitored folder (it’s usually the default, but double-check in Chrome’s settings > Downloads).
- Run the script, and it’ll run in the background waiting for new downloads. To make it run on startup, you can set it up as a background service (e.g., Windows Task Scheduler, macOS Launch Agent, Linux systemd).
Method 2: Chrome Extension + Native Messaging (Chrome-Specific & Precise)
If you want to only trigger the script when Chrome finishes a download (not just any file added to the folder), use a Chrome extension with Native Messaging. This lets the extension send a signal to your Python script right after a download completes.
High-Level Steps:
- Create a basic Chrome extension:
- Make a folder with a
manifest.jsonfile:{ "manifest_version": 3, "name": "Download Trigger", "version": "1.0", "permissions": ["downloads"], "background": { "service_worker": "background.js" }, "action": {} } - Add a
background.jsfile to listen for download completions:chrome.downloads.onChanged.addListener((downloadDelta) => { if (downloadDelta.state && downloadDelta.state.current === "complete") { // Send message to native Python script chrome.runtime.sendNativeMessage("com.yourdomain.downloadtrigger", {filePath: downloadDelta.filename.current}, (response) => { if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError); } else { console.log(response); } } ); } });
- Make a folder with a
- Set up Native Messaging for Python:
- Create a manifest file for native messaging (e.g.,
downloadtrigger.json):{ "name": "com.yourdomain.downloadtrigger", "description": "Handles Chrome download triggers", "path": "path/to/your/python/script.py", "type": "stdio", "allowed_origins": ["chrome-extension://YOUR_EXTENSION_ID/"] } - Replace
YOUR_EXTENSION_IDwith your extension’s ID (find it in Chrome’s extensions page when developer mode is on). - Install this manifest in the correct system location (varies by OS—you can test it locally first by pointing Chrome to the file directly).
- Create a manifest file for native messaging (e.g.,
- Write the Python script to receive messages:
import sys import json def process_message(message): file_path = message.get('filePath') if file_path and file_path.lower().endswith(('.png', '.jpg', '.jpeg')): print(f"Chrome download completed: {file_path}") # Run your custom task here def main(): while True: # Read message from Chrome extension raw_length = sys.stdin.read(4) if not raw_length: break message_length = int.from_bytes(raw_length, byteorder='little') message = sys.stdin.read(message_length) process_message(json.loads(message)) # Send a response back (optional) response = json.dumps({"status": "success"}).encode('utf-8') sys.stdout.write(len(response).to_bytes(4, byteorder='little')) sys.stdout.write(response) sys.stdout.flush() if __name__ == "__main__": main()
Key Notes:
- For Method 1, make sure your script runs continuously—you can minimize it or set it to start when your computer boots.
- For Method 2, you’ll need to enable developer mode in Chrome to load the unpacked extension during testing.
- Both methods work for image downloads (or any file type—just adjust the file extension checks).
内容的提问来源于stack exchange,提问作者Haris




