2016-05-07 3 views
0

Ich muss mehrere Befehle in Linux mit Python zur gleichen Zeit ausführen. Ich brauche es nicht Befehl für Befehl auszuführen.Ausführung mehrerer Befehle in Linux mit Python in der gleichen Zeit

Ich versuche, diesen Code zu schreiben, aber ich kann nicht verstehen, wie mehrere Befehle in der gleichen Zeit mit Python auch ich über Python Multithreading lesen, aber ich weiß nicht, wie man es benutzt.

Code:

# -*- 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.." 

Bitte wie kann ich mit Python tun und mehrere Befehle in der gleichen Zeit ausführen ??

+0

Sie subprocess.Popen wollen, Systembausteine –

Antwort

1

Sieht aus wie ein typisches Erzeuger-Verbraucher-Problem

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 

Hier habe ich die 5-Worker-Threads erstellt. Diese Threads werden die Funktion worker_func ausführen.
worker_func Wird ein Element aus der Liste aufnehmen und den Job vorbereiten. Wenn die Liste leer wird, kehrt die Funktion zurück (beendet).

Hinweis: Lesen Sie über Global Interpreter Lock zu verstehen, wo Python Multithreading sollte nicht verwendet werden.
In diesem Fall sollte die GIL (Global Interpreter Lock) Sie nicht beeinflussen, weil worker_func einen Subprozess aufrufen und darauf warten, dass es abgeschlossen ist. Während der Thread wartet, wird GIL für andere Threads freigegeben.

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

ich zwei Lösungen bin darauf hindeutet, aber es gibt viele

einfache Lösung:

Verwendung & am Ende Ihrer Befehle sich im Hintergrund laufen zu lassen:

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 

Threading + Queue-Lösung mit einem Steuerelement über maximal zu spawnen Threads:

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

Meine Lösung startet keine zusätzlichen Threads.
ich subprocess.Popen verwenden, um einen Befehl, zu speichern Popen Objekte in einer Liste in der ersten Schleife laufen, und warten, bis die Teilprozesse beenden in den zweiten

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) 
Verwandte Themen