如何使用 Visual Studio Code 中的参数运行 Python 程序?

问题描述 投票:0回答:6

我正在运行一个需要一些命令行参数的 Python 程序。当我在 Visual Studio Code 中构建程序时,如何提供这些参数?

python build visual-studio-code
6个回答
29
投票

您可以通过在 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


3
投票

如果您使用 Code Runner 扩展,您可以将以下内容添加到您的设置中(单击右上角的“{}”图标以获取 settings.json 文件):

“code-runner.executorMap”:{ "python": "$pythonPath -u $fullFileName xxx" }

其中 xxx 是你的论点。这是一个全局更改,因此您在处理其他文件时必须进行更改。


0
投票

在 2.0.0 版本中执行此操作的一种方法是:

"command": "python ${file} --model_type LeNet5 --prior_file conf1.json --epochs 200",

0
投票

从终端中的命令行运行脚本是可行的。


0
投票

根据 vscode 网站这里

正在添加类似

"args" : ["--port", "1593"]

launch.json


0
投票

我也在寻找这个问题的答案。在launch.json中设置是可行的,但是你只能事后使用调试,如果你有不止一种配置,就很难来回了。

所以我编写了一个简单的函数,可以在主应用程序文件中加载它。您可以使用此方法为您的参数提供一个 json 文件,它适用于调试和正常运行的脚本

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')
© www.soinside.com 2019 - 2024. All rights reserved.