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

Python调用Linux终端命令时引号转义失效问题求助

解决Python调用rostopic pub时的引号转义问题

问题根源

你代码里用的\"是HTML引号实体,并非Python的引号转义语法,导致shell解析命令时出现格式错误;同时rostopic pub的消息参数格式需要匹配shell和ROS的解析规则。

解决方案

方法1:改用ROS键值对格式(最简单)

ROS的rostopic pub支持用key:=value的键值对直接传递消息字段,完全不需要嵌套引号,Python代码直接编写即可:

import os

command = 'rostopic pub /test/fault msg/Fault name:=data_error state:=true'
os.system(command)

方法2:正确处理Python字符串转义(保留YAML格式)

如果一定要用YAML格式传递消息,用Python三重引号避免转义混乱,同时确保shell能正确识别整个YAML块:

import os

# 多行YAML格式,三重引号包裹
command = '''rostopic pub /test/fault msg/Fault "name: 'data_error'
state: true"'''
os.system(command)

# 单行YAML格式,用单引号包裹消息部分
command = "rostopic pub /test/fault msg/Fault 'name: \"data_error\" state: true'"
os.system(command)

方法3:用subprocess模块(更安全可靠)

os.system依赖shell解析命令,容易出现转义问题,推荐用subprocess.run直接传递参数列表,绕过shell的引号解析:

import subprocess

# 键值对方式
subprocess.run([
    'rostopic', 'pub', '/test/fault', 'msg/Fault',
    'name:=data_error', 'state:=true'
])

# YAML格式方式
subprocess.run([
    'rostopic', 'pub', '/test/fault', 'msg/Fault',
    'name: "data_error"\nstate: true'
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:02:40