如何在Spyder中运行含argparse的Python代码,解决-p参数缺失报错?
Ah, I’ve run into this exact issue before when working with argparse in Spyder! The problem here is that argparse expects command-line arguments to be passed when you run the script, but Spyder doesn’t automatically send those arguments by default. Let’s fix this with one of two straightforward methods:
If you’re just testing the script and want to skip messing with run configurations, you can manually pass the required arguments directly to parse_args(). Here’s how to modify your code:
ap = argparse.ArgumentParser() ap.add_argument("-p", "--shape-predictor", required=True, help="path to facial landmark predictor") ap.add_argument("-a", "--alarm", type=str, default="", help="path alarm .WAV file") ap.add_argument("-w", "--webcam", type=int, default=0, help="index of webcam on system") # Replace the path below with your actual shape predictor file path args = vars(ap.parse_args(['-p', '/absolute/path/to/your/shape_predictor.dat']))
You can add other optional arguments too if needed, like ['-p', 'your_path.dat', '-a', 'alarm_sound.wav']. Just make sure the path to your facial landmark predictor is correct (absolute paths work best to avoid confusion).
If you want to keep your code intact (so it still works from the command line), set up Spyder to pass the arguments automatically:
- Click Run in the top menu bar → select Run Configuration (or right-click your script file and choose Run with Configuration)
- In the pop-up window, find the Command line options input field
- Enter your parameters here, e.g.:
-p /absolute/path/to/your/shape_predictor.dat - Check the box for Save configuration for future runs if you don’t want to repeat this setup every time
- Click Run and your script will now receive the required arguments
Just a quick note: Double-check that your shape predictor file path is accurate—incorrect paths will lead to a "file not found" error instead!
内容的提问来源于stack exchange,提问作者Umar shan Arif

