【问题标题】:How to setup Visual Studio Code stdin/stdout redirection for Python (debugger)?如何为 Python(调试器)设置 Visual Studio Code 标准输入/标准输出重定向?
【发布时间】:2019-11-26 22:21:17
【问题描述】:

我正在使用 Visual Studio Code 调试我的 Python 代码。

我想重定向stdin 中的一个文本文件,并将输出写入另一个文件。

我可以通过使用以下语法直接运行 python 来实现:

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

有没有办法在调试脚本时允许这样做?如果那不可能,我可以创建一个配置来使用该参数运行 python。我尝试在launch.json 中使用args 参数,但这些都放在引号中,这违背了此重定向的目的。

【问题讨论】:

    标签: python visual-studio-code stdin


    【解决方案1】:

    我可以使用 launch.json 配置文件中的 args 参数来实现这一点:

    {
        // 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" ]
            }
        ]
    }
    

    运行调试器时,您会看到以下命令行:

    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 代码 1.45
    macOS 10.14.6

    【讨论】:

    • 在重定向标准输入时设置 "console": "integratedTerminal" 会引发错误:Error processing 'configurationDone' request. The handle is invalid. console 属性应该设置为 internalConsole 之类的东西。
    【解决方案2】:

    没有任何内置解决方案,但如果您修改应用以将 sys.stdin 和 sys.stdout 替换为您希望被视为 stdin 和 stdout 的内容,您可以获得相同的效果。

    【讨论】:

      猜你喜欢
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      相关资源
      最近更新 更多