Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #60349 > unrolled thread
| Started by | Devin Jeanpierre <jeanpierreda@gmail.com> |
|---|---|
| First post | 2013-11-23 20:06 -0800 |
| Last post | 2013-11-23 20:06 -0800 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Importing by file name Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-11-23 20:06 -0800
| From | Devin Jeanpierre <jeanpierreda@gmail.com> |
|---|---|
| Date | 2013-11-23 20:06 -0800 |
| Subject | Re: Importing by file name |
| Message-ID | <mailman.3115.1385266044.18130.python-list@python.org> |
On Sat, Nov 23, 2013 at 7:41 PM, Chris Angelico <rosuav@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.)
The easiest way is probably to modify what directories python searches
- sys.path:
import os
import sys
def file_import(path):
dname, fname = os.path.split(path)
modname, _ext = os.path.splitext(fname)
sys.path.insert(0, dname)
try:
return __import__(modname)
finally:
del sys.path[0]
-- Devin
Back to top | Article view | comp.lang.python
csiph-web