如何重新加载python的模块?

2024-04-25 21:20:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python实现以下方法:

def install_s3cmd():
    subprocess.call(['sudo easy_install s3cmd'])

    # assuming that by now it's already been installed
    import pexpect

    # now use pexpect to configure s3cdm
    child = pexpect.spawn('s3cmd --configure')
    child.expect ('(?i)Access Key')
    # ... more code down there

def main():
    subprocess.call(['sudo apt-get install python-setuptools']) # installs easy_install
    subprocess.call(['sudo easy_install pexpect']) # installs pexpect
    install_s3cmd()
    # ... more code down here

if __name__ == "__main__":
    main()

我需要安装pexpect,这样我就可以安装s3cmd --configurepexpect安装正确,并且在第一次执行脚本时,我得到一个错误,说它可以找到pexpect。然而,第二次运行脚本时,它的工作是完美的。可能是因为python库没有更新。如何刷新或更新python的模块,使我不再有这个问题?你知道吗


Tags: installchildmainconfiguredefmoreeasysudo
1条回答
网友
1楼 · 发布于 2024-04-25 21:20:41

当Python启动时,它会找出要搜索模块的目录,并将它们全部添加到sys.path。您看到的问题可能是因为apt安装了一个全新的目录,而Python不知道这个目录。你知道吗

我不能说这有多可靠,但是^{} module中有一些函数声称在启动时执行与Python相同的目录扫描,因此您可以尝试以下方法:

import site
import sys
sys.path[:] = site.getusersitepackages() + site.getsitepackages()

注意事项:这将而不是将当前目录留在您的路径中,如果目录在程序启动后发生了很大变化,则可能会混淆现有模块,等等

一种稍微稳健一点的方法是检查这些函数返回的列表,并将任何新的目录添加到sys.path的末尾,而不是直接替换它。你知道吗

相关问题 更多 >