検索
ホームページバックエンド開発Python チュートリアルPython で Bash サブプロセスの並列実行を実現する方法: スレッドと他のオプション?

How to Achieve Parallel Execution of Bash Subprocesses in Python: Threads vs. Other Options?

Python のマルチスレッド Bash サブプロセス

スレッドはタスクの並列化に不可欠ですが、サブプロセス モジュールと一緒にスレッドを使用するのは難しい場合があります。スレッドを介して bash プロセスを実行する場合、それらは順次に実行される傾向があります。

スレッドを使用しない並列実行

サブプロセスを並列実行するためにスレッドを使用する必要はありません。 subprocess モジュールの Popen 関数は、これを直接処理できます。

<code class="python">from subprocess import Popen

commands = ['bash commands here']
processes = [Popen(cmd, shell=True) for cmd in commands]

# Perform other tasks while processes run in parallel
for p in processes:
    p.wait()</code>

同時サブプロセスの制限

同時プロセスの数を制限するには、multiprocessing.dummy.Pool の使用を検討してください。これは multiprocessing.Pool を模倣しますが、スレッドを利用します:

<code class="python">from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call

commands = ['bash commands here']
pool = Pool(2) # Limit to 2 concurrent processes
for _, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
    if returncode != 0:
        print(f"Command failed: {returncode}")</code>

スレッドベースの代替手段

プロセス プールを使用せずに同時プロセスを制限する他のオプションには、スレッド キューの組み合わせが含まれますまたは次のアプローチ:

<code class="python">from subprocess import Popen
from itertools import islice

commands = ['bash commands here']
running_processes = []

for cmd in islice(commands, 2):
    running_processes.append(Popen(cmd, shell=True))

while running_processes:
    for i, process in enumerate(running_processes):
        if process.poll() is not None:
            running_processes[i] = next(islice(commands, 1), None)</code>

Unix 固有のソリューション

Unix ベースのシステムの場合は、上記のアプローチと組み合わせて os.waitpid() を使用することを検討してください。ビジーなループを回避します。これが Python のマルチスレッド bash サブプロセスで利用できるさまざまなオプションをカバーし、発生するシーケンシャル実行の問題に対処することを願っています。さらにご質問がございましたら、お気軽にお問い合わせください!

以上がPython で Bash サブプロセスの並列実行を実現する方法: スレッドと他のオプション?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python:編集と解釈に深く掘り下げますPython:編集と解釈に深く掘り下げますMay 12, 2025 am 12:14 AM

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?May 12, 2025 am 12:09 AM

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

ループ対pythonのループの場合:説明されたキーの違いループ対pythonのループの場合:説明されたキーの違いMay 12, 2025 am 12:08 AM

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

ループのために:実用的なガイドループのために:実用的なガイドMay 12, 2025 am 12:07 AM

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

Python:それは本当に解釈されていますか?神話を暴くPython:それは本当に解釈されていますか?神話を暴くMay 12, 2025 am 12:05 AM

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

同じ要素を持つPython Concatenateリスト同じ要素を持つPython ConcatenateリストMay 11, 2025 am 12:08 AM

ToconcatenateListsinpythothesheElements、使用:1)Operatortokeepduplicates、2)asettoremoveduplicates、or3)listcomplunting for controloverduplicates、各メトドハスディフェルフェルフェントパフォーマンスアンドソーダーインプリテーション。

解釈対編集言語:Pythonの場所解釈対編集言語:Pythonの場所May 11, 2025 am 12:07 AM

pythonisantertedlanguage、useaseofuseandflexibility-butfactingporformantationationsincriticalapplications.1)解釈されたlikepythonexecuteline-by-lineを解釈します

ループのために:Pythonでそれぞれを使用するのはいつですか?ループのために:Pythonでそれぞれを使用するのはいつですか?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境