如何在Python subprocess.Popen中使用awk?代码报错求助
解决Python f-string语法错误及K8s Pod进程ID获取问题
错误原因
你的代码中,awk命令里的{print $2}被Python的f-string解析器误认为是变量占位符(f-string用{}标识变量),但这个占位符没有合法的变量名且未正确闭合,因此触发SyntaxError: f-string: unterminated string错误。
解决方案
方案1:转义f-string中的大括号
将awk命令里的单个大括号替换为两个大括号{{}},Python会将其解析为普通大括号输出:
cs_swo_cmd = f"oc exec -it {pod_name} bash -c cs-container -- ps -eaf | grep -i 'SWe_NP' | awk '{{print $2}}'" swo_process = subprocess.Popen(cs_swo_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
方案2:优化命令,去掉多余的grep
直接用awk完成过滤和提取,减少管道进程,同时转义大括号([S]写法可避免匹配awk自身进程):
cs_swo_cmd = f"oc exec -it {pod_name} bash -c cs-container -- ps -eaf | awk '/[S]We_NP/ {{print $2}}'" swo_process = subprocess.Popen(cs_swo_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
方案3:避免shell=True(更安全)
使用列表形式传递命令参数,无需处理复杂的引号转义,还能避免shell注入风险:
cmd = [ 'oc', 'exec', '-it', pod_name, 'bash', '-c', 'cs-container -- ps -eaf | awk \'/[S]We_NP/ {print $2}\'' ] swo_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
额外提示
如果是在非交互式脚本中运行,建议去掉oc exec的-t参数(它会分配伪终端,脚本环境中可能引发异常),改为-i或直接省略:
cs_swo_cmd = f"oc exec -i {pod_name} bash -c cs-container -- ps -eaf | awk '/[S]We_NP/ {{print $2}}'"
内容的提问来源于stack exchange,提问作者Sawan Kumar
相关产品推荐
相关产品推荐

