0

Hi, I was wondering how to get around a problem I was having with eval(). I have a list of strings and each one is the name of a python file found in the same directory as the current script. I was it to import these modules to use in the current script, but: eval( "import" + modname ), where 'modname' is the script's name, causes an error. Is there any way to have the script import any found scripts or would I have to explicitly add "import <name>" for each script? Thanks!

names = [ "main", "secondary", "tertiary" ]
for item in names:
    eval( "import " + item )

The code above makes sense, but python gives me this instead:

import primary
     ^
SyntaxError: invalid syntax
4
Contributors
5
Replies
6
Views
8 Years
Discussion Span
Last Post by shadwickman
Featured Replies
  • 1

    Besides, that you do not have a "primary" module in the code... Eval evaluates an expression in his own namespace and returns the result. What you really want imho is to inject code. Something like this: [code=python] for item in names: exec "import " + item [/code] Read More

0

Try ...

names = [ "main", "secondary", "tertiary" ]
for item in names:
    cmd = "__import __(%s)" % item 
    eval( cmd )
0

I no longer got an error about the import function, but now, however, when I call a function from the "primary" module, it gives me an error saying: NameError: name 'primary' is not defined. So when I call function "draw()" from module "primary", it gives me the above error. Any ideas?

1

Besides, that you do not have a "primary" module in the code...
Eval evaluates an expression in his own namespace and returns the result.
What you really want imho is to inject code.

Something like this:

for item in names:
    exec "import " + item
Comments
good conclusion
0

Oh awesome - I got it working using exec . I never knew that it existed... Thanks for solving my problem!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.