You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python脚本内硬编码input()值并复现在线编程平台测试环境?

解决脚本内自动化输入的方案

Python 实现方式

1. 重定向 sys.stdin

直接用预定义内容替换标准输入流,适合快速调试单测试用例:

import sys
import io

# 硬编码多行输入,每行对应一次input()调用
test_input = """Alice
25
Python"""

# 重定向标准输入到内存字符串流
sys.stdin = io.StringIO(test_input)

# 原脚本逻辑
name = input("Enter name: ")
age = int(input("Enter age: "))
lang = input("Enter language: ")
print(f"Name: {name}, Age: {age}, Language: {lang}")

多测试用例可存入列表循环执行:

import sys
import io

test_cases = [
    """Alice
25
Python""",
    """Bob
30
Java"""
]

for case in test_cases:
    sys.stdin = io.StringIO(case)
    name = input()
    age = int(input())
    lang = input()
    print(f"Test result: {name}, {age}, {lang}")

2. 用 unittest.mock 模拟 input()

适合单元测试场景,精准控制每次input的返回值:

from unittest.mock import patch

# 原业务函数
def get_user_info():
    name = input("Name: ")
    age = int(input("Age: "))
    return name, age

# 模拟输入并验证结果
with patch('builtins.input', side_effect=['Charlie', '28']):
    name, age = get_user_info()
    assert name == 'Charlie'
    assert age == 28

side_effect传入列表时,每次调用input会依次取列表中的值,适配多输入场景。

3. 封装批量测试框架

自己实现类OJ的测试器,自动跑多组用例并对比结果:

def run_test(input_data, expected_output):
    import sys
    import io
    from contextlib import redirect_stdout

    # 重定向输入输出
    sys.stdin = io.StringIO(input_data)
    output_capture = io.StringIO()
    with redirect_stdout(output_capture):
        # 导入你的业务脚本主函数
        from your_script import main
        main()
    
    # 校验结果
    actual_output = output_capture.getvalue().strip()
    if actual_output == expected_output.strip():
        print("✅ 测试通过!")
    else:
        print("❌ 测试失败!")
        print(f"预期输出:\n{expected_output}")
        print(f"实际输出:\n{actual_output}")

# 定义测试用例集合
test_cases = [
    {
        'input': """10
20""",
        'expected': "30"
    },
    {
        'input': """5
5""",
        'expected': "10"
    }
]

# 执行所有测试
for idx, case in enumerate(test_cases, 1):
    print(f"\n执行测试用例 {idx}:")
    run_test(case['input'], case['expected'])

C/C++ 实现方式

1. 重定向标准输入

调试时替换stdin为文件或内存流:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
    // 用内存字符串流模拟输入
    string test_input = "Alice\n25\nPython";
    istringstream iss(test_input);
    cin.rdbuf(iss.rdbuf());

    string name;
    int age;
    string lang;
    cin >> name >> age >> lang;
    cout << "Name: " << name << ", Age: " << age << ", Language: " << lang << endl;

    return 0;
}

多测试用例可循环切换输入流:

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

void process_data(istream& input) {
    string name;
    int age;
    string lang;
    input >> name >> age >> lang;
    cout << "Result: " << name << ", " << age << ", " << lang << endl;
}

int main() {
    vector<string> test_cases = {
        "Alice 25 Python",
        "Bob 30 Java"
    };

    for (const string& case_data : test_cases) {
        istringstream iss(case_data);
        process_data(iss);
    }

    return 0;
}

2. 宏替换输入逻辑

调试阶段用宏替换输入函数,发布时取消宏定义即可:

#include <iostream>
using namespace std;

#define DEBUG_MODE
#ifdef DEBUG_MODE
#define INPUT_NAME "Alice"
#define INPUT_AGE 25
#define INPUT_LANG "Python"
#define GET_NAME(name) name = INPUT_NAME
#define GET_AGE(age) age = INPUT_AGE
#define GET_LANG(lang) lang = INPUT_LANG
#else
#define GET_NAME(name) cin >> name
#define GET_AGE(age) cin >> age
#define GET_LANG(lang) cin >> lang
#endif

int main() {
    string name;
    int age;
    string lang;
    GET_NAME(name);
    GET_AGE(age);
    GET_LANG(lang);
    cout << "Name: " << name << ", Age: " << age << ", Language: " << lang << endl;
    return 0;
}

通用优化技巧

  • 分离业务逻辑与输入读取:把核心逻辑封装成独立函数,仅接收参数,测试时直接传值,无需处理输入流。
  • 批量测试用例可存入文件,按固定格式(如分隔符、换行)划分,脚本读取后自动执行。

内容的提问来源于stack exchange,提问作者user8395964

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:33:11