On Nov 23, 2013 9:42 PM, "Chris Angelico" <ros...@gmail.com> wrote:
> 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? > The importer mechanism as far as I know only accepts module names, not filesystem paths; I believe this is by design. You could imitate it by doing something like this: import imp import sys mod = imp.new_module('spam') exec(open('/path/to/spam.py').read(), mod.__dict__) sys.modules['spam'] = mod This raises a few questions that should be addressed: Is 'spam' really the appropriate name for this module? What if there is already a different module with the name 'spam'? Presumably if the module is named 'spam' then it should be importable as 'spam', but then why the need for the path-based import? Alternatively, you might name the module something like "</path/to/spam.py>", which surely won't collide with anything imported by the normal mechanism, but then what if the spam module is also imported by normal means? You would end up with two copies of the same module with different names.
-- https://mail.python.org/mailman/listinfo/python-list