簡體   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