VS Code终端任务配置问题:输入输出文件操作返回Null值
问题原因
你当前的task.json配置里,把重定向符号<和>作为独立参数传给了Python,这会导致Python将它们当成脚本的命令行参数,而非让Shell解析输入输出重定向逻辑。你的脚本根本没读到input.txt的内容,自然输出为空(Null)。
解决方案
下面提供两种可行的修改方式:
方案一:将完整命令整合到command字段
直接把包含重定向的完整命令写在command中,args留空:
{ "version": "2.0.0", "tasks": [ { "label": "Compile and run", "type": "shell", "command": "python3 ${relativeFile} < input.txt > output.txt", "args": [], "presentation": { "reveal": "never" }, "group": { "kind": "build", "isDefault": true }, "problemMatcher": { "owner": "py", "fileLocation": [ "relative", "${workspaceRoot}" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } } } ] }
方案二:通过Shell执行命令串(适合需拆分参数的场景)
如果需要保留args结构,可以调用Shell并传入完整命令串:
{ "version": "2.0.0", "tasks": [ { "label": "Compile and run", "type": "shell", "command": "bash", "args": [ "-c", "python3 ${relativeFile} < input.txt > output.txt" ], "presentation": { "reveal": "never" }, "group": { "kind": "build", "isDefault": true }, "problemMatcher": { "owner": "py", "fileLocation": [ "relative", "${workspaceRoot}" ], "pattern": { "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$", "file": 1, "line": 2, "column": 3, "severity": 4, "message": 5 } } } ] }
额外确认点
确保你的Python脚本是从标准输入读取内容的,比如:
import sys # 读取输入内容并处理 input_content = sys.stdin.read().strip() result = int(input_content) * 2 # 假设输入为4,计算后输出8 print(result)
内容的提问来源于stack exchange,提问作者Harshal Chitte
相关产品推荐
相关产品推荐

