Python Subprocess调用7-Zip报错:系统找不到指定文件
Hey there, let's fix that frustrating "The system cannot find the file specified" error you're hitting with your 7-Zip subprocess call. There are two key issues tripping you up, and we'll walk through fixing them step by step:
1. Fix the executable path reference
You correctly built the full path to 7z.exe with progDir = os.path.join(appPath, zApp), but you're still using just 7z.exe in your command list. While you tried to work around this with the executable parameter, this approach is unreliable (especially if 7-Zip's directory isn't in your system PATH).
The simpler, more stable fix is to put the full progDir path directly as the first element in your command list, and ditch the executable argument entirely:
progDir = os.path.join(appPath, zApp) cmd = [progDir, zAction, zipFileName, zPass, zAnswer, zDir]
2. Correct the 7-Zip command line argument format
7-Zip doesn't accept the password as a standalone string. You need to prefix it with -p (so -ppassword instead of just password). If you pass the password alone, 7-Zip will treat it as a file/directory to compress—since that file doesn't exist, it throws an error that blends into the "file not found" message.
Update your password parameter and rebuild the command:
zPass = r'-ppassword' # Add the required -p prefix cmd = [progDir, zAction, zipFileName, zPass, zAnswer, zDir]
Full fixed code (with extra error checking)
Here's the complete revised code, plus a check to verify 7z.exe exists before trying to run it—this helps catch path typos early:
import subprocess import os appPath = r'C:\Users\Person\Desktop\7-Zip' zApp = r'7z.exe' zAction = r'a' zipFileName = r'C:\Users\Person\Desktop\test.zip' zPass = r'-ppassword' # Fixed password parameter zAnswer = '-y' zDir = r'C:\Users\Person\Desktop\test' progDir = os.path.join(appPath, zApp) # Pre-check if 7z.exe exists to avoid confusion later if not os.path.exists(progDir): raise FileNotFoundError(f"Couldn't find 7-Zip at: {progDir}") # Build the correct command list cmd = [progDir, zAction, zipFileName, zPass, zAnswer, zDir] # Run the command and capture output to verify success process = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, text=True) output, _ = process.communicate() if process.returncode == 0: print("Compression completed successfully!") else: print(f"Compression failed. Error details:\n{output}")
Why this worked
- The path issue: By using the full path to
7z.exein the command list, we eliminate any dependency on the system PATH finding the executable. - The parameter issue: 7-Zip now recognizes the password parameter correctly, so it doesn't try to look for a non-existent file named "password".
内容的提问来源于stack exchange,提问作者Pylander

