python - 使用 * 对 bash 命令进行子处理

标签 python bash expansion subprocess

有没有办法,我可以在 python 中执行带有扩展的 bash 命令:*

我试过千种方法都没有成功。

其实我想要一个python脚本which进入当前目录中的每个目录,并在那里执行给定的 bash 命令(可能是带有扩展名的 bash 命令:*)。

最佳答案

import os
from subprocess import check_call

cmd = 'echo *' # some shell command that may have `*`
for dirname in filter(os.path.isdir, os.listdir(os.curdir)):
    check_call(cmd, shell=True, cwd=dirname)
  • filter(os.path.isdir, os.listdir(os.curdir)) 列出当前目录的所有子目录,包括以点 (. )
  • shell=True 通过 shell 执行作为 cmd 字符串给出的命令。 * 如果存在则像往常一样由 shell 展开
  • cwd=dirname 告诉该命令应该在dirname 目录中执行

关于python - 使用 * 对 bash 命令进行子处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547501/

相关文章:

bash - Gitlab.com CI/CD ssh 权限问题

linux - bash 脚本杀死竞争条件

python - Django : Create a dynamic path with BASE_DIR

python - filterAcceptsRow() 到底做了什么?

python - numpy 矢量化/更高效的 for 循环

功能测试结果的 bash 命令分组

android - 未从 Playstore 下载 apk 扩展文件

bash - 解析和扩展区间

Makefile二次扩展

python - 使用正则表达式在 Pandas Dataframe 中创建新列