我正在运行一个Python程序,需要一些命令行参数。在Visual Studio Code中构建程序时,如何提供这些参数?
我正在运行一个Python程序,需要一些命令行参数。在Visual Studio Code中构建程序时,如何提供这些参数?
您可以通过在launch.json的args
设置中定义参数来将参数传递给程序,如下所定义:
您可以通过在launch.json的args
设置中定义参数来将参数传递给程序,如下所定义:
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"}
}
更多信息可以在此文档网站上找到:https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging#args
如果您使用Code Runner扩展程序,可以将以下内容添加到您的设置中(单击右上角的“{}”图标以获取settings.json文件):
"code-runner.executorMap": { "python": "$pythonPath -u $fullFileName xxx" }
其中xxx是您的参数。这是全局更改,因此在处理其他文件时也必须进行更改。
"command": "python ${file} --model_type LeNet5 --prior_file conf1.json --epochs 200",
在终端中从命令行运行您的脚本是可行的。
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...')
from set_args import loadArgs
loadArgs(path='args.json')