正如您所发现的,< 被 ms-python 扩展很好地放在引号内,因此 shell 不会将其视为重定向。
可以,但需要一些配置。
您必须自己设置调试客户端和服务器。
调试服务器设置为任务。客户端是附加启动配置。
首先,您需要找到作为 ms-python 扩展一部分的 debugpy 模块的位置(您可以在您的环境中作为单独的模块安装,但如果您已经拥有它,为什么要这样做)。
我使用以下 2 个文件:
redir_input.py
while True:
try:
line = input()
except EOFError:
break
print(line)
input.txt
line 1
line 2
line 3
使用redir_input.py 文件启动调试会话(从终端获取输入)。使用Ctrl+Z Enter 终止程序。
我们想要的是终端上显示的命令。比如:
<path>/.venv/Scripts/python <path>/.vscode/extensions/ms-python.python-2021.12.1559732655/pythonFiles/lib/python/debugpy/launcher 64141 -- <path>/redir_input.py
我们需要第二个字符串:debugpy 模块的位置(没有/launcher 部分)
<path>/.vscode/extensions/ms-python.python-2021.12.1559732655/pythonFiles/lib/python/debugpy
<path> 是特定于您的机器的东西。
在.vscode/tasks.json创建一个任务,启动程序进行调试:
{
"version": "2.0.0",
"tasks": [
{
"label": "Script with redirect input",
"type": "shell",
"command": "${command:python.interpreterPath} <path>/.vscode/extensions/ms-python.python-2021.12.1559732655/pythonFiles/lib/python/debugpy
--listen 5678 --wait-for-client ${workspaceFolder}/redir_input.py < ${workspaceFolder}/input.txt",
"problemMatcher": []
}
]
}
现在设置一个复合启动配置,一个启动调试服务器,一个附加调试客户端。调试服务器启动一个虚拟 python 脚本,因为我们实际上需要 prelaunchTask。
.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Attach to Process port 5678",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
}
},
{
"name": "Python: Start Process port 5678",
"type": "python",
"request": "launch",
"code": "print()",
"preLaunchTask": "Script with redirect input"
}
],
"compounds": [
{
"name": "Debug with input redir",
"configurations": [
"Python: Start Process port 5678",
"Python: Attach to Process port 5678"
]
}
]
}
选择 Debug with input redir 作为启动配置以运行(调试栏顶部),然后按运行按钮(绿色小箭头)或F5
调试器一直等到客户端附加 (--wait-for-client),您很可能想在读取行时设置断点。
将创建 2 个终端。选择正确的程序/任务运行。
您可以更改任务的名称并启动配置。请务必更新多个位置的名称。
编辑
另一种方法是更改程序的sys.stdin和sys.stdout。
然后就可以使用正常的调试方法了。
redir_input_2.py
import sys
infile = open('input.txt')
sys.stdin = infile
while True:
try:
line = input()
except EOFError:
break
print(line)
if infile: infile.close()
这里我已经硬编码了,但是当你使用特定的命令行选项时,你可以添加argparse。
redir_input_2.py --redir-input input.txt --redir-output output.txt