python - 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)
解决方案
只需正常包含它。就像是这样。无论如何,您都在使用"""
引号。
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
- 只是在阅读而不是
:
使用时分割使用的行IFS
cut
- 也就是说,不要使用 shell - 使用 python 并用 python 编写逻辑。
推荐阅读
- node.js - 机器人框架 continueDialog 没有弹出堆栈
- ios - Xcode 更新后如何修复 Core NFC 框架的无效授权
- youtube - 为什么 Google 不为其产品(如 google.com、youtube.com)使用 PWA 功能
- javascript - 使用对象过滤对象数组驻留在嵌套数组属性中
- asp.net-core - 升级到 ASP.NET Core 3.0 后,我得到“无法创建 stdoutLogFile 错误代码 = -2147024893”。
- powerbi - 是否有一个公式可以自动将数据从多列拖到新列中?
- arrays - 按类型对结构数组进行排序,然后按另一个属性按字母顺序排序
- android - 本地网络上的 Youtube Cast 按钮 Android
- python - 从给定范围python中查找所有素数
- bash - 区分用户注销和会话过期注销(SSH 和 Web 控制台)