2016-10-10 66 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()