Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #60348

Importing by file name

Date 2013-11-24 14:41 +1100
Subject Importing by file name
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3114.1385264464.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Importing by file name Chris Angelico <rosuav@gmail.com> - 2013-11-24 14:41 +1100
  Re: Importing by file name Christian Gollwitzer <auriocus@gmx.de> - 2013-11-24 10:18 +0100
    Re: Importing by file name Ian Kelly <ian.g.kelly@gmail.com> - 2013-11-24 02:50 -0700
    Re: Importing by file name Chris Angelico <rosuav@gmail.com> - 2013-11-24 22:05 +1100
    Re: Importing by file name Ian Kelly <ian.g.kelly@gmail.com> - 2013-11-24 04:37 -0700

csiph-web