How do I pass command line arguments to Python fro

2019-06-17 09:54发布

问题:

I am working with Python Tools for Visual Studio. (Note, not IronPython.)

I need to work with arguments passed to the module from the command line. I see how to start the module in Debug by right-clicking in the code window and selecting "Start with Debugging". But this approach never prompts me for command line arguments, and len(sys.argv) always == 1.

How do I start my module in debug mode and also pass arguments to it so sys.argv has more than 1 member?

回答1:

  1. Go to your project properties, either by right-clicking on the project and picking "Properties" or by picking Properties from the Project menu.

  2. Click on Debug, then enter your arguments into the "Script Arguments" field.

  3. Save.



回答2:

The steps are shown in the image linked here: https://i.stack.imgur.com/Hx5tf.png

  1. Go to debug mode in VS Code
  2. Click on the settings icon (gear icon). If it does not exist this will create a launch.json
  3. In the json, in any of the configuration, add the args json parameter:

    { "name": "Python: Terminal (integrated)", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "${config:python.pythonPath}", "program": "${file}", "cwd": "", "console": "integratedTerminal", "env": {}, "args": [ "input2.csv", "output2.csv" ], "envFile": "${workspaceFolder}/.env", "debugOptions": [], "internalConsoleOptions": "neverOpen" }

Make sure you choose that environment while debugging



回答3:

You want to select "Execute Project with Python Interactive" from the debug dropdown menu. The keyboard shortcut for this is Shift+Alt+F5. When you do that, you will have a window open at the bottom of the screen called Python Interactive and you will see your printed statements and any prompts for inputs from your program.

This does not allow you to also enter debug mode though. It is either one or the other.



回答4:

I have solved this by putting a breakpoint on the first line of my script and opening the Immediate window in VS (where you can execute commands in the context of your script). Then I run

import sys
sys.argv += 'arg1 arg2 --arg3'.split()