2017-04-24 35 views
0

下面是python函數,每個函數在大多數python函數(超過200個函數)中使用相同的重複行。如何消除python函數中的重複行

所以我打算寫它作爲模塊,並將其作爲模塊導入或任何其他建議將罰款。

下面是每個函數中出現的重複行。

def abc(username, password, host, a, b, c, d, e): 

# VARIABLES THAT NEED CHANGED 

# Create instance of SSHClient object 
    remote_conn_pre = paramiko.SSHClient() 

# Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn_pre.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 

# initiate SSH connection 
    remote_conn_pre.connect(host, username=username, password=password, look_for_keys=False, allow_agent=False) 
    print "SSH connection established to %s" % host 
# Use invoke_shell to establish an 'interactive session' 
    remote_conn = remote_conn_pre.invoke_shell() 

# Send some commands and get the output 

第二功能例如:

def xyz(username, password, host, a, b): 

# VARIABLES THAT NEED CHANGED 

# Create instance of SSHClient object 
    remote_conn_pre = paramiko.SSHClient() 

# Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn_pre.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 

# initiate SSH connection 
    remote_conn_pre.connect(host, username=username, password=password, look_for_keys=False, allow_agent=False) 
    print "SSH connection established to %s" % host 
# Use invoke_shell to establish an 'interactive session' 
    remote_conn = remote_conn_pre.invoke_shell() 

# Send some commands and get the output 

在上述功能被另一個腳本調用。 注意:下面的行在函數中並不重複。

def abc(username, password, host, a, b, c, d, e) 

和每個函數用不同的參數寫入函數(不同數量的參數)。例如像下面

def xyz(username, password, host, a, b): 
  1. 如何刪除重複的行中的所有功能,並使其沒有任何問題的工作。

上述函數用於建立ssh連接使用paramiko。

+0

「需要更改的變量」究竟是什麼? – jordanm

回答

0

你可能只是把它變成一個單獨的函數,並且把命令的名字和args一起傳遞給函數。類似這樣的:

def run_remote(username, password, host, command, *command_args): 
    # Create instance of SSHClient object 
    remote_conn = paramiko.SSHClient() 

    # Automatically add untrusted hosts (make sure okay for security policy in your environment) 
    remote_conn.set_missing_host_key_policy(
    paramiko.AutoAddPolicy()) 

    # initiate SSH connection 
    remote_conn.connect(host, 
         username=username, 
         password=password, 
         look_for_keys=False, 
         allow_agent=False) 
    print "SSH connection established to %s" % host 
    # execute a remote command and return stdin, stdout, stderr 
    args_as_str = ' '.join([pipes.quote(arg) for arg in command_args]) 
    return remote_conn.exec_command("{} {}".format(command, args_as_str) 
+0

''args_as_str = ['''應該是'args_as_str =''.join(...)',也''pipes.quote''''''' –

+0

@DanD。更新,好抓。 – jordanm

+0

* command_args表示多個參數?請解釋一下 – asteroid4u