简体   繁体   English

Python3 脚本中的复杂 Bash 循环结构

[英]Complex Bash loop structure in Python3 script

I want to run a (complex) Bash while loop from a Python3 script.我想从 Python3 脚本运行(复杂的)Bash while 循环。 I know os.subprocess and os.subprocess.check_output works in this case, but I can't wrap my head around how to include the while inside a Python subprocess.我知道 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

I've tried the following:我尝试了以下方法:

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)

Just include it normally.只需正常包含它。 Like it is.就像是这样。 You are using """ quotes anyway.无论如何,您都在使用"""引号。

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)

Notes:笔记:

  • you should export mida environment variable before using it.您应该在使用之前导出mida环境变量。 When $mida variable is not set will result in some [: something expected but not there messages.$mida变量未设置时,将导致一些[: something expected but not there消息。
  • printf "$(stuff)" | wc -c printf "$(stuff)" | wc -c ? printf "$(stuff)" | wc -c Just stuff | wc -c只是stuff | wc -c stuff | wc -c . stuff | wc -c
  • Check your scripts with http://shellcheck.net使用http://shellcheck.net检查您的脚本
  • Read https://mywiki.wooledge.org/BashFAQ/001阅读https://mywiki.wooledge.org/BashFAQ/001
  • Just split the line on : using IFS when reading instead of using cut只需将行拆分为:阅读时使用IFS而不是使用cut
  • And that said, do not use shell - use python and write the logic in python.也就是说,不要使用 shell - 使用 python 并将逻辑写入 python。

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

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