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

使用pytest向Bash脚本传递字符串时结果被截断的问题

问题:Python调用Bash脚本时带空格的参数被截断

相关代码

Python测试脚本

from subprocess import check_output
from datetime import datetime

def run_shell_test(script, *args):
    out = check_output([script] + list(args), universal_newlines=True)
    return out.split("\n")[0]

def test_log_2():
    message = "This is a test message"
    now = datetime.now()

    result = run_shell_test('./tests/test_log.sh', f"{message}")
    assert result == f"[{now.strftime('%Y-%m-%d %H:%M')}] {message}"

Bash功能脚本(./tests/test_log.sh)

print_log() {
  log_date=$(date "+%Y-%m-%d %H:%M")
  echo "[$log_date] $1"
}

# 脚本需包含函数调用逻辑,否则无输出
print_log "$1"

测试结果

  • pytest执行异常输出:
[2022-12-13 11:56] This
  • 预期输出:
[2022-12-13 11:56] This is a test message
  • 直接运行Bash脚本的正常输出:
print_log "This is a test message"
[2022-12-13 08:31] "This is a test message"

问题原因

使用subprocess.check_output的列表形式传参时,Python会自动将每个列表元素作为独立的命令行参数传递,不需要手动添加引号。你在Python中传递f"{message}"时,字符串本身不含引号,Bash脚本收到参数后会按空格分割,$1只能取到第一个单词"This"。而直接在Bash中运行时,引号是Shell的语法,用来将整个字符串标记为单个参数,所以$1能拿到完整内容。

解决方案

直接传递原始字符串参数即可,不需要额外加引号。修改Python测试函数中的调用:

result = run_shell_test('./tests/test_log.sh', message)

这样Python会把整个message作为单个参数传给Bash脚本,$1就能拿到完整的带空格的字符串,断言也会符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:10:27