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:
But that's not importing. Is there a way to do this as a module import?
ChrisA
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:
Hello, world!g={}
exec("def __main__():\n\tprint('Hello, world!')\n",g)
g["__main__"]()
But that's not importing. Is there a way to do this as a module import?
ChrisA