3

I was wondering if it's possible with my python script to install a module before trying to import it. When I run my script now it will try to import the modules (of course) but I want it to install the modules, then check if it can import it.

Update 1

This is my install script I wanna use to install it on run of script:

def install():
print("\nChecking for dependencies, please stand by...")
with hideInfo():
    if str(os.name) == 'nt':
        easy_install.main(['textract'])
        pip.main(['install', 'logging'])
        pip.main(['install', 'datetime'])
    else:
        pip.main(['install', 'textract'])
        pip.main(['install', 'logging'])
        pip.main(['install', 'datetime'])

time.sleep(1)
menu()
Nerotix
  • 335
  • 3
  • 16

3 Answers3

1

For any future individuals who stumble on this, here is a link to an easy way to accomplish this inside a single script

https://stackoverflow.com/a/24773951/3754128

0

Sure.

  1. Install programmatically, then try to import (as opposed to installing from command line)

  2. Just add an import statement to the end of your existing install script, if it's already programatic


# normal installation routine
try:
    import foobar        
except ImportError:
   panic()
  1. Call an external install command in python (sudo apt-get install python-foobar, e.g.)

Things to Consider

  • Often, to install a package, you need elevated privileges or sudo power. You may not want the rest of your python runtime to have those powers too, so installing separately can avoid danger (if you're doing file processing, e.g.)
  • Most installation scripts will already report if they fail. Doing the extra check isn't inherently useful.
  • Installing things without people's permission can be annoying for them. If you are distributing this script, I would advise against it. I don't want a package I download to overwrite my numpy distribution because it thought it was a good idea
  • If you're installing it to the local directory, then trying to import from the local directory, that won't neccessarily be a great indicator that the installed package is accessible from your whole computer. This may or may not be a problem
Community
  • 1
  • 1
en_Knight
  • 4,793
  • 1
  • 23
  • 40
  • Thanks for your answer, I'm not a 100% sure what you mean. But I update my post with my install function. I call this function in my main. – Nerotix Feb 03 '16 at 15:12
0

I fixed it in a different way. I used a module called "importlib". With this I was able to make a try and except way of trying to import the module and if it doesn't work, install it.

Nerotix
  • 335
  • 3
  • 16