繁体   English   中英

“错误:未知速记标志:'f' in -f5”从 Python 运行 bash 脚本时

[英]“Error: unknown shorthand flag: 'f' in -f5” when running bash script from Python

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

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

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 helm list | grep prod- | cut -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

尽量避免从高级语言运行复杂的 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命令使其在执行时打印出每一行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM