0

I have a script that looks like this:

import pip
import sys

def main(argv):
    ...[does stuff]...

if __name__ == "__main__":
    main(sys.argv[1:])

I would like to implement this function i found on stack that imports a package (or install it if nescessary).

def import_or_install(package):
try:
    __import__(package)
except ImportError:
    pip.main(['install', package])

My vision is that if i run a script on a random computer, if the packaged needed to run said script are not installed, the script does it automatically; Otherwise, import the module.

When I try to run it, I get a NameError stating that the modules I call within main() are not defined.

Link to where I found the function: Check if module exists, if not install it

  • 1
    What's the actual question? Where are you having problems? what doesn't work, or do you need advice on? – match Jan 17 '18 at 16:57
  • BTW, if you're asking about something you found in a different SO question or answer, it's courteous to link to that answer. (But *do* be sure your question actually contains a question -- a description of a specific problem, or exact steps to take to see something not work and a description of how to *tell* it's not working, etc). – Charles Duffy Jan 17 '18 at 16:59
  • I've never done it but you might want to use `venv` (virtual environment) in order to avoid tampering with the destination machine. – Camion Jul 14 '20 at 19:27

1 Answers1

0

What I understand in Question, if something like this :

import pip

not_installed = []

try:
 import test1

except ImportError,err:
    k= str(err).split(' ')
    not_installed.append(k[-1])

for i in not_installed:
   pip.main(['install',i])

Here test1 is the file to be run, convert it to cli accordingly

P.S: Checked for 1 import error message

DARK_C0D3R
  • 2,075
  • 16
  • 21
  • See [How to Answer](https://stackoverflow.com/help/how-to-answer), particularly the section "Answer well-asked questions", particularly the first bullet point: Answers for questions which "*are unclear or lacking specific details that can uniquely identify the problem*" should not be attempted; instead, the OP should be asked to clarify to provide a specific, answerable question. – Charles Duffy Jan 17 '18 at 18:04
  • Yeah, at first I tried to comment to clarify but didn't have enough repo as new user so, I answered it. Ok I'll keep that it mind next time – DARK_C0D3R Jan 17 '18 at 18:10
  • Does that need to be ran inside the main function(), or inside the "if __name__" statement? – JimmyBuffet_Express Jan 17 '18 at 19:04
  • Yes, actually here I showed to run another file by importing it to this file – DARK_C0D3R Jan 18 '18 at 09:08