首页 > 解决方案 > Python3 脚本中的复杂 Bash 循环结构

问题描述

我想从 Python3 脚本运行(复杂的)Bash while 循环。我知道 os.subprocess 和 os.subprocess.check_output 在这种情况下有效,但我无法理解如何将 while 包含在 Python 子进程中。

while read -r line
do
    if [ "$(echo "$line" | cut -d : -f 7)" = "/bin/bash" ] && [ $(printf "$(echo "$line" | cut -d : -f 1)" | wc -c) -gt $mida ]
    then
        echo $line | cut -d : -f 1
    fi
done < /etc/passwd

我尝试了以下方法:

out=subprocess.check_output(""" while read -r line; do; if [ "$(echo "$line" | cut -d : -f 7)" = "/bin/bash" ] && [ $(printf "$(echo "$line" | cut -d : -f 1)" | wc -c) -gt $mida ]; then; echo $line | cut -d : -f 1; fi; done < /etc/passwd """, shell=True)

标签: pythonbash

解决方案


只需正常包含它。就像是这样。无论如何,您都在使用"""引号。

out = subprocess.check_output("""
while read -r line
do
    if [ "$(echo "$line" | cut -d : -f 7)" = "/bin/bash" ] && [ $(printf "$(echo "$line" | cut -d : -f 1)" | wc -c) -gt $mida ]
    then
        echo $line | cut -d : -f 1
    fi
done < /etc/passwd
""", shell=True)

笔记:

  • 您应该在使用它之前导出mida环境变量。未设置变量时$mida会产生一些[: something expected but not there消息。
  • printf "$(stuff)" | wc -c? 只是stuff | wc -c
  • 使用http://shellcheck.net检查您的脚本
  • 阅读https://mywiki.wooledge.org/BashFAQ/001
  • 只是在阅读而不是:使用时分割使用的行IFScut
  • 也就是说,不要使用 shell - 使用 python 并用 python 编写逻辑。

推荐阅读