I am running a Python program that takes some command line arguments. How can I provide these arguments when I am building a program within the Visual Studio Code?
You can pass in the arguments into the program by defining the arguments in the args
setting of launch.json as defined below:
json
{
"name": "Python",
"type": "python",
"pythonPath":"${config.python.pythonPath}",
"request": "launch",
"stopOnEntry": true,
"console": "none",
"program": "${file}",
"cwd": "${workspaceRoot}",
"args":["arg1", "arg2"],
"env": {"name":"value"}
}
Further information can be found on the documentation site here: https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging#args
Run without debugging
option, it'll still use the same options and it will not debug your code –
Mulvihill If you use the Code Runner extension you can add the following to your settings (click on the '{}' icon in the top right corner to get the settings.json file):
"code-runner.executorMap": { "python": "$pythonPath -u $fullFileName xxx" }
where xxx is your argument. This is a global change so you have to change when working on other files.
One way to do it in the version 2.0.0 is:
"command": "python ${file} --model_type LeNet5 --prior_file conf1.json --epochs 200",
running your script from the command line in the terminal works.
I was also looking for an answer for this. Setting in launch.json works, but you can only use debugging afterwards and if you have more that one configuration, it makes it hard to go back and forth.
So I write a simple function that I can load in main app file. You can give your args with a json file with this method and it works for both debugging and normally running script
import sys
import json
def loadArgs(path):
with open(path) as args_file:
args = json.load(args_file)
for arg in args:
name = '--' + arg
value = args[arg]
if name not in sys.argv:
sys.argv.append(name)
sys.argv.append(value)
print('Args are loaded...')
And import in your main file
from set_args import loadArgs
loadArgs(path='args.json')
© 2022 - 2024 — McMap. All rights reserved.