Importing by file name

Chris Angelico rosuav at gmail.com
Sat Nov 23 22:41:00 EST 2013


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):

>>> import "/x.py"
SyntaxError: invalid syntax
>>> importlib.import_module("/x.py")
ImportError: No module named '/x'
>>> importlib.import_module("/x")
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



More information about the Python-list mailing list