【问题标题】:subprocess a bash command with *使用 * 子处理 bash 命令
【发布时间】:2012-03-03 16:02:54
【问题描述】:

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

我尝试了数千种方法,但没有运气。

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

【问题讨论】:

  • 其实不看代码就很难说出如何解决你的问题。
  • @IgnacioVazquez-Abrams:我不认为这是重复的,因为答案是一样的。我们希望人们能够搜索问题,而不是答案,对吧?
  • @machine:他们都问如何将 glob 与子进程一起使用。
  • @Ignacio Vazquez-Abrams:如果它是重复的,那么my answer 也应该回答the question that you've linked,但肯定不是。

标签: python bash expansion subprocess


【解决方案1】:
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 目录中执行

【讨论】:

  • 它完全按照我的意愿工作,但为什么 check_callcwd arg 和 python docs 没有任何关系。
  • @Adobe:文档明确提到 “完整的函数签名与 Popen constructor 的签名相同 - 此函数将所有提供的参数直接传递到该接口。”
【解决方案2】:

您可能对glob module?有用吗

>>> import glob
>>> glob.glob("*")
['build', 'DLLs', 'Doc', 'ez_setup.py', 'foo-bar.py', 'include', 'Lib', 'libs','LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Removesetuptools.exe', 'Scripts', 'selectitems.py', 'selectitems.pyc', 'setuptools-wininst.log', 'share', 'so_vector.py', 'tcl', 'Tools', 'w9xpopen.exe']
>>>

【讨论】:

  • 我知道 glob,但我想将 bash 命令作为 Python 脚本的参数。
【解决方案3】:

既然你要让 shell 执行命令,就让 shell 来扩展 shell 元字符。你可以运行:

sh -c "your_commaand -with *"

shell 会为你处理 globbing 并执行命令。

这给您留下了遍历当前目录的子目录的问题。必须有一个 Python 模块才能做到这一点。

如果你决定你的程序应该chdir()到子目录,你必须小心在处理完每个子目录后回到起始目录。或者,shell 也可以为你处理这个问题,使用:

sh -c "cd relevant-subdir; your_command -with *"

这避免了问题,因为 shell 是一个单独的进程切换目录而不影响您的主要 Python 进程。

【讨论】:

  • +1:我从来没有想过——我可以将它提供给bash -c
猜你喜欢
  • 2018-08-16
  • 2011-09-15
  • 2014-11-30
  • 2014-04-04
  • 2018-04-06
  • 1970-01-01
  • 2017-01-27
  • 2021-01-12
相关资源
最近更新 更多