Fundamentals 15 min read

Mastering Python Built‑ins: print, input, open, eval, and exec for Test Automation

This tutorial demonstrates how to harness Python's built‑in functions—print, input, open, eval, and exec—to customize console logs, write test results to files, create interactive scripts, safely evaluate strings, and dynamically load code, while highlighting common pitfalls and security considerations.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Mastering Python Built‑ins: print, input, open, eval, and exec for Test Automation

print()

Customize console output using the sep parameter to join objects with a chosen delimiter and the end parameter to suppress the trailing newline.

# basic usage (default space separator, newline at end)
print("接口登录测试", "状态码:200", "耗时:0.5s")

# advanced usage: custom separator and no newline (useful for progress bars)
print("2026-07-11", "POST /api/login", "200 OK", sep=" | ", end=" >>> ")
print("断言通过")

Redirect output to a file with the file argument inside a context manager.

# write to a file and auto‑close
with open("test_report.txt", "w", encoding="utf-8") as f:
    print("测试用例1:登录接口", file=f)
    print("测试结果:PASS", file=f)

# append mode with explicit flush to avoid log loss
with open("test_report.txt", "a", encoding="utf-8") as f:
    print("测试用例2:订单接口", "FAIL", sep=" | ", file=f, flush=True)

input()

Collect user input; the function always returns a string. A prompt can be supplied.

# simple prompt
env = input("请输入要测试的环境 (test/prod): ")
print(f"即将开始 {env} 环境的接口测试...")

# obtain multiple values in one line and split them
info = input("请输入 接口路径 和 期望状态码 (空格分隔): ").split()
print(f"准备测试接口: {info[0]},期望状态码: {info[1]}")

Validate numeric input with try‑except and repeat until a valid value is entered.

# basic validation
try:
    threads = int(input("请输入并发线程数: "))
    print(f"设置线程数为: {threads}")
except ValueError:
    print("输入无效,必须是纯数字!")

# loop until a positive integer is provided
while True:
    try:
        timeout = int(input("请输入接口超时时间(秒): "))
        if timeout > 0:
            break
        print("超时时间必须大于0,请重新输入")
    except ValueError:
        print("格式错误,请输入整数")
print(f"超时时间已设置为: {timeout}秒")

open()

Read configuration files line‑by‑line, optionally filtering comment lines that start with #.

# simple line reading
with open("config.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(f"读取到接口: {line.strip()}")

# filter out empty lines and comments
with open("config.txt", "r", encoding="utf-8") as f:
    apis = [line.strip() for line in f if line.strip() and not line.startswith("#")]
    print(f"有效接口数量: {len(apis)}")

Append test execution details to a log file.

# append mode using write()
with open("run.log", "a", encoding="utf-8") as f:
    f.write("2026-07-11 10:00:00 | /api/user | PASS
")

# append mode using print(..., file=f)
with open("run.log", "a", encoding="utf-8") as f:
    print("2026-07-11", "/api/order", "FAIL", "耗时:2.1s", sep=" | ", file=f)

eval()

Convert a string representation of a Python literal into an actual object, perform simple calculations, or evaluate dynamic assertions.

# string to dict
resp_str = '{"code": 200, "msg": "success"}'
resp_dict = eval(resp_str)
print(f"状态码是: {resp_dict['code']}")

# simple arithmetic
calc_str = "100 * 2 + 50"
result = eval(calc_str)
print(f"接口响应计算结果: {result}")

# dynamic boolean assertion
response = {"age": 20}
assertion = "response['age'] > 18"
print(f"断言结果: {eval(assertion)}")

# safe eval with restricted globals
safe_dict = {"__builtins__": {}}
result = eval("response['age'] == 20", safe_dict, {"response": response})
print(f"安全断言结果: {result}")

# extract nested field
data = {"user": {"name": "Alice", "age": 25}}
path = "data['user']['name']"
print(f"提取到的名字: {eval(path)}")

# batch conversion from a file where each line is a dict string
with open("data.txt", "r") as f:
    dataset = [eval(line.strip()) for line in f if line.strip()]
    print(f"共加载 {len(dataset)} 条测试数据")

exec()

Execute arbitrary Python code strings, dynamically define functions or classes, and load external scripts.

# execute a multi‑line snippet
code = "x = 10
y = 20
print(f'动态计算和: {x+y}')"
exec(code)

# load an external helper file
with open("auth_helper.py", "r") as f:
    exec(f.read())
print("鉴权模块加载完毕")

# execute code in a custom namespace and retrieve variables
namespace = {}
exec("BASE_URL = 'https://api.test.com'
TIMEOUT = 30", namespace)
print(f"加载的配置: {namespace['BASE_URL']}")

# dynamically define a test function
func_code = "def test_login():
    assert 1 + 1 == 2"
exec(func_code)
test_login()
print("动态函数执行成功")

# generate multiple test functions in a loop
for i in range(3):
    exec(f"def test_api_{i}():
    print(f'正在执行接口 {i}')")

test_api_0()
test_api_1()

Combined built‑ins for interactive tools and reports

Build a simple interactive menu with print and input, and generate a Markdown‑style test report using exec.

# interactive menu
while True:
    print("
=== 自动化测试工具箱 ===")
    print("1. 造数据  2. 跑回归  3. 退出")
    opt = input("请选择: ").strip()
    if opt == '3':
        print("已退出")
        break
    elif opt in ('1', '2'):
        print(f"正在执行任务 {opt}…")
    else:
        print("无效选项,请重新输入")

# dynamic report generation
report_code = "print('--- 测试报告 ---')
print('通过: 10, 失败: 2')"
exec(report_code)

results = {"pass": 10, "fail": 2}
code = f"print(f'通过率: {results['pass']}/(results['pass']+results['fail'])*100:.1f}%')"
exec(code)

Practical notes

Use eval and exec only with trusted code; they can execute arbitrary commands.

Avoid input() in CI/CD pipelines because the process will block without a console.

When writing logs with print(..., file=f), enable flush=True to ensure data is persisted on crashes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythondata processingtest automationexecevalprintinputopen
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.