Importing by file name

C

Chris Angelico

As part of a post on python-ideas, I wanted to knock together a quick
little script that "imports" a file based on its name, in the same way
that the Python interpreter will happily take an absolute pathname for
the main script. I'm sure there's a way to do it, but I don't know
how. Obviously the import statement can't do it, but I've been poking
around with __import__ and importlib without success. (Experiments are
being done on Python 3.3; if a different version would make the job
easier I'm happy to switch. This is just a curiosity tinkering.)

Here's my current attempts (tracebacks chomped as they aren't very
helpful here):
ImportError: No module named '/x'

The best I can come up with is manually execing the file contents:
g={}
exec("def __main__():\n\tprint('Hello, world!')\n",g)
g["__main__"]()
Hello, world!

But that's not importing. Is there a way to do this as a module import?

ChrisA
 
I

Ian Kelly

Undocumented... that explains why I didn't know about it! But that
does appear to be what I'm looking for, so is there some equivalent
planned as a replacement?

Hmm, playing around with importlib a bit, this seems to work:

from importlib import find_loader
loader = find_loader('spam', ['/path/to'])
if loader is not None:
module = loader.load_module()

The path passed to find_loader is searched instead of sys.path.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top