如何在Python的subprocess.run中执行bash的echo命令?
问题原因与解决方法
现象原因
当使用subprocess.run并设置shell=True时,数组参数的传递逻辑发生了变化:
- 默认情况下,
shell=True会启动/bin/sh(Raspbian Stretch中为dash),数组的第一个元素作为shell程序路径,后续元素会被当作shell的命令行参数,而非直接传递给echo。 - 你的代码相当于执行:
/bin/sh -c echo -n -e 'Hello World\n',这里shell的-c选项只会接收第一个后续参数echo作为要执行的命令,剩下的-n、-e、Hello World\n都会变成shell自身的位置参数($1、$2、$3),根本没传给echo命令。 - 最终
echo在没有任何参数的情况下执行,默认输出换行符,所以你得到的结果是b'\n'。
解决方法
方法1:移除shell=True,直接执行echo(推荐)
echo是系统可执行程序(路径通常为/bin/echo),无需shell解析参数,直接用数组传递参数即可:
python3 -c 'import subprocess; result=subprocess.run(["echo", "-n", "-e", r"Hello World\n"], check=True, stdout=subprocess.PIPE); print(result.stdout)'
执行后会得到预期的b'Hello World\n'(-n会抑制echo默认添加的末尾换行,但你传入的Hello World\n中的换行符仍会被输出)。
方法2:保留shell=True,传递完整命令字符串
如果必须依赖shell的特性(如通配符、管道等),需将整个命令作为单个字符串传递,而非数组:
python3 -c 'import subprocess; result=subprocess.run("echo -n -e \"Hello World\n\"", shell=True, check=True, stdout=subprocess.PIPE); print(result.stdout)'
或者使用原始字符串避免转义:
python3 -c 'import subprocess; result=subprocess.run(r"echo -n -e \"Hello World\n\"", shell=True, check=True, stdout=subprocess.PIPE); print(result.stdout)'
补充:指定bash执行(匹配测试环境)
由于你在bash中测试echo命令正常,但shell=True默认使用dash,若需完全匹配bash的行为,可指定启动bash执行命令:
python3 -c 'import subprocess; result=subprocess.run(["bash", "-c", "echo -n -e \"Hello World\n\""], check=True, stdout=subprocess.PIPE); print(result.stdout)'
内容的提问来源于stack exchange,提问作者sdbbs
相关产品推荐
相关产品推荐

