Home > Software design >  Way to use command-line arguments with "Python: Run Python file in Terminal" in VSCode?
Way to use command-line arguments with "Python: Run Python file in Terminal" in VSCode?

Time:09-06

Command line arguments in VSCode work fine when setup in the launch.json file.

But when using "Python: Run Python file in Terminal" (run, not debug), the arguments in launch.json don't seem to appear in sys.argv.

Is there a way to pass command line arguments to Python code when using "Python: Run Python file in Terminal"?

CodePudding user response:

Vscode is just an editing shell, which is essentially a CMD command window. If you only use run in terminal, it will only run the file in the terminal without getting command line parameters.

You have the following alternative solutions:

  1. Run with debug and define args in the launch.json file.

  2. use method parser.add_argument() to pass arguments in your codes. For example:

    import argparse

    parser = argparse.ArgumentParser(description="para transfer")

    parser.add_argument("--para", type=str, default="helloWorld", help="para -> str type.")

    args = parser.parse_args()

    print(args)

  3. Manually run Python file in terminal and pass parameters.

    python test.py --para helloworld

  4. Try extension code-runner, you can set the custom command to run in the settings.json:

{

   "code-runner.customCommand": "echo Hello"

}

CodePudding user response:

You can pass arguments via args inside of the JSON.

Sample:

{
     "version": "0.2.0",
     "configurations": [
         {
             "name": "Python: app.py",
             "type": "python",
             "request": "launch",
             "program": "${workspaceFolder}/app.py",
             "args" : ["arg1", "arg2", "arg3"]
         }
     ]
 }

Source: VSCode

  • Related