2

I'm implementing the following method in 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()

I need to have pexpect installed, so I can install s3cmd --configure. pexpect is installed correctly, and in the first time the script is executed, I get an error saying it could find pexpect. However, the second time I run the script it work flawless. It's probably because python libraries hasn't been updated. How can I refresh, or update the python's module so I don't have that problem again?

2
  • incidentally: rather than shelling out to sudo (!), you might want to just write a setup.py for this script and let a tool like pip install the dependencies for you. Commented Feb 10, 2014 at 22:58
  • @Eevee I will do that eventually Commented Feb 10, 2014 at 23:07

1 Answer 1

2

When Python starts up, it figures out which directories to search for modules, and adds them all to sys.path. The problem you're seeing is probably because apt installs a whole new directory, which Python then doesn't know about.

I can't say how reliable this is, but there are functions in the site module that claim to do the same directory scanning as Python does on startup, so you could try this:

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

Caveats: this will not leave the current directory in your path, it might confuse existing modules if the directories have changed a lot since the program started, etc.

A slightly more robust approach would be to check through the lists returned by those functions and add any new directories to the end of sys.path, rather than replace it outright.

Sign up to request clarification or add additional context in comments.

2 Comments

local variable 'pexpect' referenced before assignment ... that's what happened
perhaps you need to post more of your code; that shouldn't happen given what's in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.