Skip to main content
 首页 » 编程设计

python之预期方法不起作用

2025年04月02日8zhoujg

我运行的是CentOS7,在Python3.5中安装了pexpect。但是,当我调用任何方法时,它返回一个错误,指出该属性不存在。任何想法为什么会这样?我读到这可能是由于目录中的文件名为 pexpect.py,但我在同一目录中没有名为 pexpect.py 的文件。

$ pip3.5 freeze | grep pexpect 
pexpect==4.2.1 

示例代码:

# This connects to the openbsd ftp site and 
# downloads the recursive directory listing. 
import pexpect 
child = pexpect.spawn('ftp ftp.openbsd.org') 
child.expect('Name .*: ') 
child.sendline('anonymous') 
child.expect('Password:') 
child.sendline('noah@example.com') 
child.expect('ftp> ') 
child.sendline('lcd /tmp') 
child.expect('ftp> ') 
child.sendline('cd pub/OpenBSD') 
child.expect('ftp> ') 
child.sendline('get README') 
child.expect('ftp> ') 
child.sendline('bye') 

错误:

CentOS7 虚拟机错误:

/usr/local/bin/python3.5 /media/sf_PycharmProjects/MyPyScripts/Tutorials/input_cmds 
Traceback (most recent call last): 
  File "/media/sf_PycharmProjects/MyPyScripts/Tutorials/input_cmds", line 4, in <module> 
    child = pexpect.spawn('ftp ftp.openbsd.org') 
AttributeError: module 'pexpect' has no attribute 'spawn' 

Windows 错误:

Traceback (most recent call last): 
  File "C:/Users/home/PycharmProjects/PyCAT/Current_Version/SFTP/testsftp.py", line 4, in <module> 
    child = pexpect.spawn('ftp ftp.openbsd.org') 
AttributeError: module 'pexpect' has no attribute 'spawn' 

预期目录:

>>> import pexpect 
>>> dir(pexpect) 
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__'] 

请您参考如下方法:

好吧,对于 Windows 错误,我可以告诉您 Pexpect.spawn 在 Windows 上不起作用。这必须与 pypi 做一些事情,它只在 linux 系统上提供一些模块,而 spawn 使用其中一个部分。

在 Windows 上,您必须改用 PopenSpawn。