I thought I would write this up as a quick blog post. I’m really impressed with VS Studio, after years of working in Eclipse based IDE’s it seems fast and smooth. Setting up command line arguments for the code you are working on however seems harder than you would expect. While in Eclipse there is an option to configure runtime arguments on the menu it is more hidden in VS Code.
Configuring command line arguments in VS Studio Code
To set-up your runtime arguments you need to edit your launch.json file which lives within your projects .vscode directory.
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "args": ["Demo.xml", "42"] } ] }
You need to add the “args” configuration option line. This key takes a list of arguments which will then be available in your code.
Using command line arguments in your Python code
In your code you can then do something like this:
#Check the program has been called with the Excel Spreadsheet filename and Account Number if len(sys.argv) != 3: print(sys.argv) print("Usage ,") sys.exit(1) else: # argv[0] in Python is always the name of the script. inputFile = sys.argv[1] inputAccount = sys.argv[2] print(sys.argv)
This works when you press F5 to run the code or start a debug session.
Alternative to command line arguments
Above I have explained how to set-up command line arguments / parameters for your Python programs using Microsoft VisualCode Studio. It works but it’s more work than it should be in a modern IDE. So in my more recent code I’ve started to prompt the user to enter missing parameters rather than just tell them they are missing. It’s not much work and actually makes your program more user friendly.
Here is a simple example:
# Check the program has been called with the a Customer ID if len(sys.argv) < 1: print("Usage <Account Number>) customerID = input('Enter customer ID :') else: # argv[0] in Python is always the name of the script. customerID = sys.argv[1]
In this code instead of just giving an error message and exiting when the program hasn’t been called with the right parameters we ask the user to enter the missing parameters at runtime. This is more helpful when debugging and also more user-friendly for the end user.
Recommended books for Microsoft Visual Studio Code
Visual Studio Code Distilled, for MacOS, Linux and Windows. Published by Apress.
0 Comments