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

Python/Bash中如何对感叹号'!'进行转义?

解决方法

方法1:双重转义感叹号

在Python字符串里,要让Bash识别到\!,需要把反斜杠也转义,写成\\!:

c.run('sqlcmd -U nrv -P PP\\!asword -Q "select top 3 * from sys.databases"', pty=True)

方法2:使用原始字符串

原始字符串不会解析转义字符,直接写\!即可:

c.run(r'sqlcmd -U nrv -P PP\!asword -Q "select top 3 * from sys.databases"', pty=True)

方法3:拆分命令为列表(更推荐)

直接传递命令参数列表,完全避开Shell转义问题,兼容性和可读性更好:

c.run(['sqlcmd', '-U', 'nrv', '-P', 'PP!asword', '-Q', 'select top 3 * from sys.databases'], pty=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:31:16