“错误:未知速记标志:-f5中的'f',当从Python运行bash脚本时

问题描述 投票:0回答:1

运行一个简单的python脚本时遇到问题,该脚本从helm脚本读取.sh命令并输出。

当我直接在终端中运行命令时,它运行正常:

helm list | grep prod- | cut -f5

# OUTPUT: prod-L2.0.3.258

但是当我运行python test.py(请参见下面的test.py的完整源代码)时,会收到错误消息,好像我正在运行的命令是helm list -f5而不是helm list | grep prod- | cut -f5

user@node1:$ python test.py

# OUTPUT:
# Opening file 'helm_chart_version.sh' for reading...
# Running command 'helm list | grep prod- | cut -f5'...
# Error: unknown shorthand flag: 'f' in -f5

test.py脚本:

import subprocess

# Open file for reading
file = "helm_chart_version.sh"

print("Opening file '" + file + "' for reading...")
bashCommand = ""
with open (file) as fh: 
    next(fh) 
    bashCommand = next(fh)

print("Running command '" + bashCommand + "'...")

process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()

if error is None:
    print output
else:
    print error

helm_chart_version.sh的内容:

cat helm_chart_version.sh

#  OUTPUT: 
## !/bin/bash
## helm list | grep prod- | cut -f5
python linux bash shell kubernetes-helm
1个回答
0
投票

[尝试避免从高级语言运行复杂的Shell管道。给定您显示的命令,您可以将helm list作为子进程运行,然后在Python中对其进行后处理。

process = subprocess.run(["helm", "list"], capture_output=True, text=True, check=True)
for line in process.stdout.splitlines():
  if 'prod-' not in line:
    continue
  words = line.split()
  print(words[4]) 

您显示的实际Python脚本在语义上似乎与直接运行Shell脚本没有什么不同。您可以使用sh -x选项或shell set -x命令使它在执行时打印出每一行。

© www.soinside.com 2019 - 2024. All rights reserved.