[英]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:笔记:
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
。:
using IFS
when reading instead of using cut
只需将行拆分为:
阅读时使用IFS
而不是使用cut
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.