小编use*_*739的帖子

Python - 如何使用 kwargs 从类创建对象或调用方法

我有以下带有 kwargs init 的父类:

class A(object):
    """ Parent class """
    def __init__(self, **kwargs):     

        # connect parameters
        self.host           = kwargs.get('host', 'localhost')
        self.user           = kwargs.get('user', None)
        self.password       = kwargs.get('password', None)

    def connect(self):
        try:           
            self.ConnectWithCred( self.host, 
                                  self.port, 
                                  self.user,
                                  self.password)
        except pythoncom.com_error as error:
            e = format_com_message("Failed to connect")
            raise Error(e)
Run Code Online (Sandbox Code Playgroud)

我想创建一个“类 A”的对象并调用“连接”方法。我该怎么办?我尝试了以下操作,但它无法运行(仅供参考 - 我是 Python 新手):

sub_B = A(self.host = 'example.com', self.port = 22, self.user = 'root', 
          self.password = 'testing')
sub_B.connect()
Run Code Online (Sandbox Code Playgroud)

python keyword-argument

7
推荐指数
1
解决办法
2301
查看次数

pexpect - 无法运行示例,不断收到 AttributeError: 'module' 对象没有属性 'spawn'

我正在运行 Python3 并尝试运行 sshls.py 脚本,但总是失败:

AttributeError:“模块”对象没有属性“spawn”

我尝试运行为:

python3 sshls.py
Run Code Online (Sandbox Code Playgroud)

我什至修改了脚本来设置 env 或 python 脚本,但仍然失败:

#!/usr/bin/python3
Run Code Online (Sandbox Code Playgroud)

或者

#!/usr/bin/env python3
Run Code Online (Sandbox Code Playgroud)

我尝试使用 python2.7 仍然得到相同的错误。

脚本内容:

from __future__ import print_function
 
from __future__ import absolute_import
 
import pexpect
import getpass, os, traceback
def ssh_command (user, host, password, command):
     ssh_newkey = 'Are you sure you want to continue connecting'
     child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
     i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
     if i == 0: # Timeout
         print('ERROR!')
         print('SSH could not login. Here is …
Run Code Online (Sandbox Code Playgroud)

python pexpect

5
推荐指数
1
解决办法
4万
查看次数

Python - 如何将ctime转换为'%m /%d /%Y%H:%M:%S'

有没有直接的方法将ctime值转换为'%m /%d /%Y%H:%M:%S'格式?

例如,将"Wed Nov 6 15:43:54 2013"​​转换为"11/06/2013 15:43:54"

我尝试了以下但没有给我我想要的格式,这是"11/06/2013 15:43:54":

>>> t = time.ctime()
>>> f = datetime.datetime.strptime(t, '%a %b %d %H:%M:%S %Y')
>>> print f
2013-11-06 15:43:54
Run Code Online (Sandbox Code Playgroud)

但是,如果我将它直接传递给time.strftime,它将需要9项序列:

>>> n = time.strftime(t, '%D %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Run Code Online (Sandbox Code Playgroud)

python datetime

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×3

datetime ×1

keyword-argument ×1

pexpect ×1