0

This code indicates what I wish to do, i.e.

  • Have a variable to hold the name of a file to import,
  • Use shutil.which() to look up the FOLDER it resides in (via $PATH),
  • Automatically get that added to PYTHONPATH to make import find it.
name='numbas'  
d=os.path.dirname(shutil.which(name+'.py'))  
sys.path.append(d)  
from name import *  

Now import does not allow a name stored in a variable.
eval() on a string that contains the import statement is also "nonfunctional".

Any ideas on how to get this thing to actually work?

The reason for all this is that I have *.py scripts in a Util/ -folder - which are self-contained scripts AND import modules for other scripts to utilize.

If I move these around or copy them to a friend I wish to have the folder structure remain as is.

1
  • 3
    To import a module with a specified name, you can use the function importlib.import_module. Commented Dec 4 at 15:33

1 Answer 1

0

Right, timez.py used as command line script, and by importing and calling main() :

The fact that you get a "<module>" back from importlib.import_module(name) was not clear from the docs I found. a type(...) revealed it though. I would have expected it to be added in the same manner as with a pure import.

$ ./timez.py 10 1000 20
... has rotated 100.0 revs/hour at 2.0 rpm in average, while utilized 50.0% of the power hours.

$ python -c "import importlib;name='timez'; timez=importlib.__import__(name);timez.main(['mama',10, 1000, 20])"
... has rotated 100.0 revs/hour at 2.0 rpm in average, while utilized 50.0% of the power hours.

$ python -c "import importlib;name='timez'; timez=importlib.import_module(name);timez.main(['mama',10, 1000, 20])"
... has rotated 100.0 revs/hour at 2.0 rpm in average, while utilized 50.0% of the power hours.
Sign up to request clarification or add additional context in comments.

Comments

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.