Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup Visual Studio Code stdin/stdout redirection for Python (debugger)?

I am using Visual Studio Code to debug my Python code.

I want to redirect one text file in stdin and the output be written in another file.

I can reach that by running python directly using the following syntax:

python code.py < input.txt > output.txt

Is there a way to allow that while debugging the script? If that is not possible, can I create a configuration for running python with that parameters. I tried using args parameter in the launch.json, but those are all placed into quotes that defeats the purpose of this redirection.

like image 333
Alexander Galkin Avatar asked Nov 26 '19 22:11

Alexander Galkin


People also ask

How do I enable Python debugger in Visual Studio Code?

If you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File in Terminal.

How do I run a Python program in Visual Studio Code terminal?

Just click the Run Python File in Terminal play button in the top-right side of the editor. Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.


2 Answers

I was able to achieve this using the args parameter in the launch.json config file:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387

    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Aktuelle Datei",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "args": [ "<", "input.txt",
                 ">", "output.txt" ]
        }
    ]
}

When running the debugger you get the following command line:

bash-3.2$  env DEBUGPY_LAUNCHER_PORT=51669 /usr/local/opt/python/bin/python3.7 /Users/XXXX/.vscode/extensions/ms-python.python-2020.4.76186/pythonFiles/lib/python/debugpy/wheels/debugpy/launcher "/Users/XXXX/my_script.py" < input.txt > output.txt 

Visual Studio Code 1.45
macOS 10.14.6

like image 143
Volker Voecking Avatar answered Oct 06 '22 04:10

Volker Voecking


There isn't any built-in solution, but if you modified your app to replace sys.stdin and sys.stdout with what you would like to be considered stdin and stdout you could get the same effect.

like image 43
Brett Cannon Avatar answered Oct 06 '22 03:10

Brett Cannon