3

My code is this:

for module in ["ffmpy","os","sys"]:
    try:
        __import__(module)
    except:
        print("Can't import ["+module+"]")

So, I want to import this globally, but it doesn't seem to do this. After this code, I have sys.path.insert(0, r"C:\Users\david\Desktop\scripts"),and the python console tells me: NameError: name 'sys' is not defined. I don't know what I'm doing wrong, but you hopefully do.

edit: This Question is not a duplicate, because i don't 'just' want to import from string, but do that from a for loop. I basically want to import from a string, in a loop, globally.

Riedler
  • 375
  • 4
  • 11
  • 2
    I can see why you might want to conditionally handle importing of `ffmpy`, but `os` and `sys`…?! If those don't exist… then what?! – deceze Nov 20 '18 at 11:48
  • @deceze I think the question is interesting even without the `try-except` block. – Ma0 Nov 20 '18 at 11:50
  • @deceze Well I did that because of lazy programming, but I get your point. I just wrote everything to import in that line. – Riedler Nov 20 '18 at 11:51
  • Possible duplicate of [import module from string variable](https://stackoverflow.com/questions/8718885/import-module-from-string-variable) – Tobias Brösamle Nov 20 '18 at 11:53
  • 1
    Well, don't be lazy. It's *good* that `import` raises exceptions if things can't be imported, and you would need a really good reason to want to suppress those. – deceze Nov 20 '18 at 11:54
  • The module has been imported but not bound to the name `sys` in your scope. – Stop harming Monica Nov 20 '18 at 11:55

1 Answers1

5

I think the issue is that although you have imported the library sys you haven't defined the object sys.

Consider the two following examples:

# Doesn't work
__import__('sys')
sys.callstats()

This throws the same error: "name 'sys' is not defined", while

# Works
sys = __import__('sys')
sys.callstats()

works fine.

You need to store the imported objects somewhere. A dictionary seems sensible:

import_dict = dict()

for module in ["ffmpy","os","sys"]:
    try:
        import_dict[module] = __import__(module)
    except:
        print("Can't import ["+module+"]")


import_dict['sys'].path.insert(0, r"C:\Users\david\Desktop\scripts")

Should work.

Edit:

As suggested by @9769953 in the comments, an even better solution is to use:

globals()[module] = __import__(module)

which then allows you to access sys directly as you would normally.

Andrew McDowell
  • 2,860
  • 1
  • 17
  • 31
  • 2
    Or if you really want, use `globals()[module] = __import__(module)` and then use `sys` and others directly, as in `sys.path.insert(0, r"C:\Users\david\Desktop\scripts")`. – 9769953 Nov 20 '18 at 12:10