2016-09-13 2 views
0

Zum Beispiel:Wie wird eine Variable in Fabric ssh iteriert?

global count 
count += 1 
@task 
def install(hosts, local_swift_config): 
    env.use_ssh_config = True 
    env.hosts = set_hosts(hosts) 
    execute(place_count) 

def place_count(): 
    sudo('echo {} > /home/user/some_count'.format(count)) 
    count += 1 

Es ist keine globale, was die bevorzugte Art und Weise dies mit Stoffe zu tun ist, sein muss?

Antwort

1
count = 0 
@task 
def install(hosts, local_swift_config): 
    env.use_ssh_config = True 
    env.hosts = set_hosts(hosts) 
    execute(place_count) 

def place_count(): 
    sudo('echo {} > /home/user/some_count'.format(count)) 
    global count 
    count += 1 

Ich hatte diese Arbeit für einfache Funktionen in Stoff. Ihr Problem ist mit Python Globals, nicht mit Fabric.

Siehe diesen Thread für weitere Informationen über Globals: Stacokverflow Python Globals

+0

Danke, ich beschlossen, nicht 'zu verwenden global' und ging stattdessen mit der Variable 'env'. Danke für die Köpfe hoch. Ich hatte noch nie zuvor ein globales verwendet und war an dem Punkt, an dem ich alles genutzt hätte, was auf Kosten der guten Praxis funktioniert hätte. – jmunsch

0

entschied ich mich nicht global zu verwenden:

def counter(): 
    env.count += 1 
    if env.count == 2: 
     env.count += 4 

@task 
def install(hosts): 
    env.count = 0 

    execute(counter) 
    print(env.count) 

    execute(counter) 
    print(env.count) 

    execute(counter) 
    print(env.count) 

Ouput:

1 
6 
7 

Done. 
Verwandte Themen