方法はありますか、Python で bash コマンドを展開して実行できます。*
私は何千もの方法を試しましたが、うまくいきませんでした。
実際には、現在のディレクトリの各ディレクトリに入り、そこで特定の bash コマンドを実行するpython スクリプトが必要です(おそらく、展開された bash コマンド*
)。
方法はありますか、Python で bash コマンドを展開して実行できます。*
私は何千もの方法を試しましたが、うまくいきませんでした。
実際には、現在のディレクトリの各ディレクトリに入り、そこで特定の bash コマンドを実行するpython スクリプトが必要です(おそらく、展開された 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
cmd
シェルを介して文字列として指定されたコマンドを実行します。*
存在する場合は、通常どおりシェルによって展開されますcwd=dirname
dirname
コマンドをディレクトリで実行する必要があることを示しますシェルにコマンドを実行させるため、シェルにシェル メタキャラクタの展開を行わせます。以下を実行できます。
sh -c "your_commaand -with *"
シェルがグロビングを処理し、コマンドを実行します。
そのため、現在のディレクトリのサブディレクトリをトラバースするという問題が残ります。これを行うには、Python モジュールが必要です。
プログラムをchdir()
サブディレクトリに移動する必要があると判断した場合は、各ディレクトリを処理した後、開始ディレクトリに戻るように注意する必要があります。または、次を使用して、シェルもそれを処理できます。
sh -c "cd relevant-subdir; your_command -with *"
シェルは、メインの Python プロセスに影響を与えずにディレクトリを切り替える個別のプロセスであるため、これにより問題が回避されます。
>>> 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']
>>>