如何在Visual Studio 2015中固定Flask项目运行端口为5000
Hey there! As someone who’s dealt with those frustrating random port numbers back in my early Flask days with VS 2015, I totally get how annoying it is to have a new port pop up every time you run your project. Let me walk you through two simple, reliable ways to lock it to port 5000:
Method 1: Hardcode the Port in Your Flask Script
This is the most straightforward fix—just tell your Flask app exactly which port to use directly in your code. Find the section where you call app.run() and add the port parameter:
from flask import Flask app = Flask(__name__) # Your routes and app logic go here... if __name__ == '__main__': app.run(port=5000, debug=True) # Added port=5000 to lock the port
Now, whether you run the script through VS or directly, your app will always start on port 5000. The debug=True flag is optional but handy for auto-reloading when you make code changes.
Method 2: Configure Visual Studio’s Debug Settings
If you’d rather not hardcode the port (maybe you want flexibility for different environments), you can set it directly in VS 2015’s project settings:
- Right-click your Flask project in the Solution Explorer and select Properties
- Switch to the Debug tab
- Look for the Script arguments field and enter
--port 5000 - Click Save to apply the changes
Next time you hit "Start Debugging", VS will pass this argument to your Flask app, forcing it to use port 5000 instead of generating a random one.
Either method should solve your problem—pick whichever fits your workflow better!
内容的提问来源于stack exchange,提问作者Lutaaya Huzaifah Idris

