2016-05-07 19 views
0

Linuxでpythonを使って複数のコマンドを同時に実行する必要があります。 コマンドでコマンドを実行する必要はありません。Linuxでpythonを使って複数のコマンドを同時に実行する

私はこのコードを書いてみるが、私のpythonを使用して、同じ時間に複数のコマンドを実行する方法を理解することはできませんまた、私はPythonのマルチスレッドについて読んしかし、私はそれを使用する方法がわかりません。

コード:

# -*- coding: utf-8 -*- 

import os 

commands = ['ping www.google.com', 'ping www.yahoo.com', 'ping www.hotmail.com'] 
count = 0 
for com in commands: 
    print "Start execute commands.." 
    os.system(com) 
    count += 1 
    print "[OK] command "+str(count)+" runing successfully." 
else: 
    print "Finish.." 

私のpythonでそれを行うと、同じ時間で複数のコマンドを実行することができますか?

+0

で終了します –

答えて

1

は、典型的な生産者 - 消費者問題

import threading 
import os 

commands = ['ping www.google.com', 'ping www.yahoo.com', 'ping www.hotmail.com'] 

def worker_func(): 
    while commands: # Checks if the the list is not-empty. Loop exits when list is becomes empty 
     com = commands.pop(0) 
     print "Start execute commands.." 
     os.system(com) 
     count += 1 
     print "[OK] command "+str(count)+" runing successfully." 

workers = [threading.Thread(target=worker_func, args=tuple(), name='thread_'+str(i)) for i in range(5) ] # Create 5 workers (consumers) 
[worker.start() for worker in workers] # Start working 
[worker.join() for worker in workers] # Wait for all workers to finish 
ここ

私は5つのワーカースレッドを作成しているように見えます。これらのスレッドは、機能worker_funcを実行します。
worker_funcリストから要素を1つ取り出してジョブを実行します。リストが空になると、関数は戻ります(終了します)。

注:Global Interpreter Lockについては、Pythonマルチスレッドを使用しないでください。 worker_funcコールサブプロセスとは完全にそれを待つので、この場合
はGIL(グローバルインタプリタロック)があなたに影響を与えるべきではありません。スレッドが待機している間、GILは他のスレッドに解放されます。私は2つの解決策を示唆していますが、多くの

シンプルなソリューションがある

0
import threading 
import os 


def ping_url(number): 

    os.system(number) 

thread_list = [] 
commands = ['ping www.google.com', 'ping www.yahoo.com', 'ping www.hotmail.com'] 
for url in commands: 
    # Instantiates the thread 

    t = threading.Thread(target=print_number, args=(url,)) 
    # Sticks the thread in a list so that it remains accessible 
    thread_list.append(t) 

# Starts threads 
for thread in thread_list: 
    thread.start() 

# This blocks the calling thread until the thread whose join() method is called is terminated. 
# From http://docs.python.org/2/library/threading.html#thread-objects 
for thread in thread_list: 
    thread.join() 

# Demonstrates that the main process waited for threads to complete 
print "Done" 
2

使用&は、バックグラウンドでそれらを実行するために、あなたのコマンドの末尾に:

commands = ['ping www.google.com &', 'ping www.yahoo.com &', 'ping www.hotmail.com &'] 
for com in commands: 
    os.system(com) # now commands will run in background 

スレッド+最大スレッド数を制御するキューソリューション:

from Queue import Queue, Empty 
import threading, os 

def worker_func(): 
    while not stopped.is_set(): 
     try: 
      # use the get_nowait() method for retrieving a queued item to 
      # prevent the thread from blocking when the queue is empty 
      com = q.get_nowait() 
     except Empty: 
      continue 
     try: 
      os.system(com) 
     except Exception as e: 
      print "[-] Error running command %s" %(str(e)) 
     finally: 
      q.task_done() 

commands = ['ping www.google.com', 'ping www.yahoo.com', 'ping www.hotmail.com'] 

thread_count = 4 # maximum parallel threads 
stopped = threading.Event() 
q = Queue() 
print "-- Processing %s tasks in thread queue with %s thread limit" %(str(len(commands)), str(thread_count)) 

for item in commands: 
    q.put(item) 

for i in range(thread_count): 
    t = threading.Thread(target=worker_func) 
    # t.daemon = True #Enable to run threads as daemons 
    t.start() 
q.join()  # block until all tasks are done 
stopped.set() 
1

私の解決策では余分なスレッドが開始されません。
私は最初のループでは、リスト内の店舗Popenオブジェクトを、コマンドを実行し、サブプロセスまで待つsubprocess.Popenを使用するには、あなたがsubprocess.Popen、システム・ブロックをしたい二

from subprocess import Popen, PIPE 

commands = ['ping www.google.com', 'ping www.yahoo.com', 'dir'] 
count = 0 
processes = [] 
for com in commands: 
    print "Start execute commands.." 
    processes.append(Popen(com, shell=True)) 
    count += 1 
    print "[OK] command "+str(count)+" running successfully." 
else: 
    print "Finish.." 

for i, process in enumerate(processes): 
    process.wait() 
    print "Command #{} finished".format(i) 
関連する問題