Search code examples
powershellvisual-studio-code

How to provide a file as std input in VSCode (Windows, python)?


Rather than typing the standard input via the terminal, I'd like to have my python program in VS code to read the standard input from an input file (say, input.txt). This is a common setup to easily work on competitive programming problems.

According to this blogpost, a way to do this is to provide this arg in launch.json:

"args": ["<", "${workspaceFolder}/input"]

Which makes sense because hello.py < input.txt is how I roughly expect this to work. However when I tried this on my Windows, the terminal gives me this error:

The '<' operator is reserved for future use.

Similar comments here : https://stackoverflow.com/a/61755465/2613667 and https://stackoverflow.com/a/69744570/2613667 indicat that others also ran into the issue when trying this trick in Windows. Apparently powershell doesn't support the '<' operator?

How do I work around this?


Solution

  • On Windows, Visual Studio Code uses PowerShell as the default shell, and PowerShell doesn't support input redirection via <.

    Thus, in your scenario you must specify a shell that does support <, notably cmd.exe.

    Unfortunately, there seems to be no way to specify the shell to use as part of given launch configuration in launch.json.

    Therefore, you have two options:

    • Option A: Make Command Prompt (i.e., cmd.exe) the default shell profile, which by default determines both the shell to use interactively as well as - unless overridden (see below) - for automation operations, i.e. operations relating to launch (debug) configurations (launch.json) and tasks (tasks.json):

      • Open the Settings view (Ctrl+,) and navigate to TerminalIntegratedDefault Profile: Windows; searching for default profile windows should be enough to locate it.

      • Select Command Prompt from the dropdown list.

    • Option B: More narrowly and therefore preferably, you can make cmd.exe the default shell for automation operations only:

      • Open your settings.json file for editing as follows: From the command palette (select menu command View > Command Palette... or press Ctrl+Shift+P to open it), select command Preferences: Open User Settings (JSON); searching for user json should be enough to locate it.

      • Add the following top-level property:

        "terminal.integrated.automationProfile.windows": {
          "path": "cmd.exe"
        }