skip to Main Content

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"?

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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"
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search