2016-10-10 64 views
0

此處的總noob。我試圖創建一個python對象並在其中的一個實例中執行方法,似乎我想執行的代碼塊不會運行。問題中的代碼塊是run_job,它在被調用時似乎什麼都不做。我究竟做錯了什麼?未執行Python方法

import datetime 
import uuid 
import paramiko 


class scan_job(object): 

    def __init__(self, protocol, target, user_name, password, command): 
     self.guid = uuid.uuid1() 
     self.start_time = datetime.datetime.now() 
     self.target = target 
     self.command = command 
     self.user_name = user_name 
     self.password = password 
     self.protocol = protocol 
     self.result = "" 

    def run_job(self): 
     if self.protocol == 'SSH': 
      ssh = paramiko.SSHClient() 
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
      try: 
       print "creating connection" 
       ssh.connect(self.target, self.user_name, self.password) 
       print "connected" 
       stdin, stdout, stderr = ssh.exec_command(self.command) 
       for line in stdout: 
        print '... ' + line.strip('\n') 
        self.result += line.strip('\n') 
       yield ssh 
      finally: 
       print "closing connection" 
       ssh.close() 
       print "closed" 

     else: 
      print "Unknown protocol" 

    def show_command(self): 
     print self.command 


test = scan_job('SSH', '192.168.14.10', 'myuser', 'mypassword', 'uname -n') 

test.show_command() 

test.run_job() 
+0

你已經寫了發電機的方法,以'yield'聲明。這是你的意思嗎?生成器創建惰性迭代器。 –

+0

刪除'yield ssh'。無論如何,我不知道你爲什麼擁有它。 –

回答

0

您的方法包含一個yield語句,它使它成爲一個生成器。發電機組被懶惰地評估。考慮:

>>> def gen(): 
... yield 10 
... yield 3 
... yield 42 
... 
>>> result = gen() 
>>> next(result) 
10 
>>> next(result) 
3 
>>> next(result) 
42 
>>> 

這可能不是你打算做的。

+1

爲什麼downvote? –

+0

不是我,而是在猜測,因爲它不回答問題。我看到你已經提到了一些關於發電機的觀點,但是這與OP的問題有什麼關係呢? –

+0

@PaulRooney你真的不能推斷,還是你暗示我應該更明確? –

0

產量是一個像返回一樣使用的關鍵字,除了該函數將返回一個生成器 。

想了解更多關於發電機:
1)Understanding Generators in Python
2)What does the "yield" keyword do in Python?
3)Understanding the Yield Keyword in Python

所有你需要做的是,更改:

yield ssh 

要:

return ssh 

因此,run_job將像普通函數一樣執行,直到達到其結尾,異常或返回語句。但是,如果您想在不更改yield語句的情況下運行它。這裏是你如何能做到這:

x = test.run_job() 
x.next()