Skip to main content
 首页 » 编程设计

python之在子进程下使用 pexpect 有错误

2025年05月04日11soundcode

我使用pexpect的pxssh模型写了一个ssh自动登录程序。 但是当我在 multiprocessing 中使用相同的程序时,会发生此错误:

Exception in thread Thread-2: 
Traceback (most recent call last): 
  File "/usr/local/zenoss/lib/python2.6/threading.py", line 525, in __bootstrap_inner 
    self.run() 
  File "/usr/local/zenoss/lib/python2.6/threading.py", line 477, in run 
    self.__target(*self.__args, **self.__kwargs) 
  File "/usr/local/zenoss/lib/python2.6/multiprocessing/pool.py", line 259, in _handle_results 
    task = get() 
TypeError: ('__init__() takes exactly 2 arguments (1 given)', <class 'pexpect.EOF'>, ()) 

这是我的代码:

import pxssh 
import multiprocessing 
 
class ssh_linux: 
    def __init__(self,q_host,linux_user,linux_pwd,linux_su_passwd,linux_port): 
        timeout=5 
        status,shell=self.ssh_login(q_host,linux_user,linux_pwd,timeout,linux_port) 
        #i think this error-------- 
        if status: 
            print 'conn ok!' 
            self.set_env(shell) 
 
    def ssh_login(self,q_host,linux_user,linux_pwd,timeout,linux_port): 
        status=0 
        try: 
            s = pxssh.pxssh() 
            s.login (q_host,linux_user,linux_pwd,port=linux_port,auto_prompt_reset=True,login_timeout=timeout) 
            status=1 
        except pxssh.ExceptionPxssh, e: 
            s=str(e) 
            print "ssh login fail!",s 
            status=0 
        return status,s 
 
def do_calculation(data): 
    run=ssh_linux(q_host,linux_user,linux_pwd,linux_su_passwd,linux_port) 
 
def main():      
    pool_size = multiprocessing.cpu_count() * 2 
    pool = multiprocessing.Pool(processes=pool_size,initializer=start_process,) 
    pool.map(do_calculation,input_list) 
    pool.close() 
    pool.join() 

请您参考如下方法:

谢谢大家。 我找到了解决办法。

这个问题是我的:代码不规范 我把我的代码改成这样,返回就OK了:

    self.hostname = q_host 
    self.username = linux_user 
    self.password = linux_pwd 
    self.su_pw=linux_su_passwd 
    self.port=linux_port 
    status,shell=self.ssh_login(self.hostname,self.username,self.password,self.timeout,self.port)