如何用Python在树莓派3上自动打印文件夹中新JPEG文件
Hey there! Let's get this auto-printing setup working for you step by step. You're already off to a great start with the folder monitoring script—we just need to tweak it for Python 3, add JPEG filtering, and hook up the CUPS printing functionality.
Step 1: Fix & Enhance the Folder Monitoring Script
Your original script uses Python 2 syntax (like the unparenthesized print statements) which won’t work on Python 3.5. Let’s update it to only track JPEG files and handle incomplete file writes (so you don’t try printing a file that’s still being saved to the folder):
import os import time path_to_watch = '/home/pi/jebenter/' # Cover all common JPEG extension variations JPEG_EXTENSIONS = ('.jpg', '.jpeg', '.JPG', '.JPEG') # Initialize the set of tracked JPEG files before = set() for f in os.listdir(path_to_watch): file_path = os.path.join(path_to_watch, f) if os.path.isfile(file_path) and f.endswith(JPEG_EXTENSIONS): before.add(f) def is_file_ready(file_path): """Check if the file is fully written and accessible""" try: with open(file_path, 'rb'): return True except (PermissionError, IOError): return False while True: time.sleep(2) # Adjust interval based on how fast you need detection after = set() for f in os.listdir(path_to_watch): file_path = os.path.join(path_to_watch, f) if os.path.isfile(file_path) and f.endswith(JPEG_EXTENSIONS): after.add(f) # Find newly added JPEGs added_jpegs = after - before if added_jpegs: print(f"Detected new JPEGs: {', '.join(added_jpegs)}") for filename in added_jpegs: full_path = os.path.join(path_to_watch, filename) # Wait until the file is fully saved before printing while not is_file_ready(full_path): time.sleep(0.5) # Call our print function (defined next) print_jpeg(full_path) # Update tracked files for the next loop before = after
Step 2: Add the CUPS Printing Function
Since your CUPS service is already running, you have two solid options to print from Python:
Option 1: Use the lp Command (No Extra Libraries Needed)
The lp command is built into CUPS, so we can call it directly with Python’s subprocess module. First, find your printer’s name by running lpstat -p in the terminal (look for the line starting with device for <printer_name>).
Add this function to your script:
import subprocess def print_jpeg(file_path): # Replace with your printer's name from lpstat -p PRINTER_NAME = "your_printer_name" try: # Send the file to the printer via CUPS result = subprocess.run( ['lp', '-d', PRINTER_NAME, file_path], check=True, capture_output=True, text=True ) print(f"Successfully sent {file_path} to printer: {result.stdout}") except subprocess.CalledProcessError as e: print(f"Failed to print {file_path}: {e.stderr}")
Option 2: Use pycups (Pythonic CUPS Integration)
If you prefer a native Python library instead of shell commands, install a Python 3.5-compatible version of pycups first:
pip install pycups==2.0.1
Then add this print function:
import cups def print_jpeg(file_path): # Connect to the local CUPS server conn = cups.Connection() # Get available printers (use your printer's name from lpstat -p) PRINTER_NAME = "your_printer_name" if PRINTER_NAME not in conn.getPrinters(): print(f"Printer {PRINTER_NAME} not found! Available printers: {list(conn.getPrinters().keys())}") return try: # Send the JPEG to the printer job_id = conn.printFile(PRINTER_NAME, file_path, "Auto-Print JPEG", {}) print(f"Print job submitted successfully! Job ID: {job_id}") except cups.IPPError as e: print(f"Failed to send print job: {e}")
Step 3: Test & Tweak
- Verify printer connectivity first: Manually print a test JPEG with
lp -d your_printer_name /path/to/test.jpgto confirm CUPS is working. - Adjust monitoring interval: The
time.sleep(2)in the loop can be shortened or lengthened based on how quickly you need to detect new files. - Optional: Add file archiving: To avoid re-printing files if the script restarts, add code to move printed JPEGs to an archive folder after printing.
内容的提问来源于stack exchange,提问作者Marije Miedema

