472,353 Members | 1,490 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,353 software developers and data experts.

How can I import a script with an arbitrary name ?

Hi all,

I have a script responsible for loading and executing scripts on a
daily basis. Something like this:

import time
t = time.gmtime()
filename = t[0] + '-' + t[1] + '-' + t[2] + '.py'
import filename

So, I have a module with an arbitrary file name and I want to load it,
and later access its function definitions.
How can I do this ? In my example, the last line will obviously not
work.

Oct 30 '06 #1
10 2566
wrote in news:11**********************@i42g2000cwa.googlegr oups.com in
comp.lang.python:
Hi all,

I have a script responsible for loading and executing scripts on a
daily basis. Something like this:

import time
t = time.gmtime()
filename = t[0] + '-' + t[1] + '-' + t[2] + '.py'
import filename

So, I have a module with an arbitrary file name and I want to load it,
and later access its function definitions.
How can I do this ? In my example, the last line will obviously not
work.
http://docs.python.org/lib/built-in-funcs.html

The first one __import__ should do the trick.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Oct 30 '06 #2
le***********@gmail.com wrote:
I have a script responsible for loading and executing scripts on a
daily basis. Something like this:

import time
t = time.gmtime()
filename = t[0] + '-' + t[1] + '-' + t[2] + '.py'
import filename

So, I have a module with an arbitrary file name and I want to load it,
and later access its function definitions.
execfile() is probably your best bet:

namespace = {}
execfile(filename, namespace)

namespace["function"](argument)

also see:

http://effbot.org/zone/import-string...ng-by-filename

</F>

Oct 30 '06 #3
I had to do something like this a while back for a modular IRC bot that
I wrote.
__import__() will do the trick, however to avoid getting a cache of the
module I recomend doing something like...

mod = reload( __import__("%s-%s-%s" % ( t[0], t[1], t[2] ) ) )
le***********@gmail.com wrote:
Hi all,

I have a script responsible for loading and executing scripts on a
daily basis. Something like this:

import time
t = time.gmtime()
filename = t[0] + '-' + t[1] + '-' + t[2] + '.py'
import filename

So, I have a module with an arbitrary file name and I want to load it,
and later access its function definitions.
How can I do this ? In my example, the last line will obviously not
work.
Oct 30 '06 #4
le***********@gmail.com writes:
So, I have a module with an arbitrary file name and I want to load it,
and later access its function definitions.
How can I do this ? In my example, the last line will obviously not
work.
If you want a solution that gives you an actual module object, here's
what I use:

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(module_name)

module_file = open(file_name, 'r')
exec module_file in module.__dict__

return module

--
\ "A celebrity is one who is known by many people he is glad he |
`\ doesn't know." -- Henry L. Mencken |
_o__) |
Ben Finney

Oct 30 '06 #5
On Tue, 31 Oct 2006 11:00:52 +1100, Ben Finney wrote:
If you want a solution that gives you an actual module object, here's
what I use:

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(module_name)

module_file = open(file_name, 'r')
exec module_file in module.__dict__

return module
Isn't that awfully complicated? What's wrong with using __import__ to get
a module object?
>>mod = __import__("math")
mod
<module 'math' from '/usr/lib/python2.4/lib-dynload/mathmodule.so'>
The only advantage (or maybe it is a disadvantage?) I can see to your
function is that it doesn't search the Python path and you can specify an
absolute file name.
--
Steven.

Oct 31 '06 #6
Steven D'Aprano wrote:
The only advantage (or maybe it is a disadvantage?) I can see to your
function is that it doesn't search the Python path and you can specify an
absolute file name.
that's the whole point of doing an explicit load, of course. if you
think that's a disadvantage, you haven't done enough plugin work...

</F>

Oct 31 '06 #7
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auwrites:
On Tue, 31 Oct 2006 11:00:52 +1100, Ben Finney wrote:
If you want a solution that gives you an actual module object,
here's what I use:

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

The only advantage (or maybe it is a disadvantage?) I can see to
your function is that it doesn't search the Python path and you can
specify an absolute file name.
Which is exactly what the OP asked for (though he didn't necessarily
need a module object).

--
\ "We have to go forth and crush every world view that doesn't |
`\ believe in tolerance and free speech." -- David Brin |
_o__) |
Ben Finney

Oct 31 '06 #8
On Tue, 31 Oct 2006 12:44:50 +0100, Fredrik Lundh wrote:
Steven D'Aprano wrote:
>The only advantage (or maybe it is a disadvantage?) I can see to your
function is that it doesn't search the Python path and you can specify an
absolute file name.

that's the whole point of doing an explicit load, of course. if you
think that's a disadvantage, you haven't done enough plugin work...
Guilty as charged.

--
Steven.

Oct 31 '06 #9
On Tue, 31 Oct 2006 22:53:56 +1100, Ben Finney wrote:
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auwrites:
>On Tue, 31 Oct 2006 11:00:52 +1100, Ben Finney wrote:
If you want a solution that gives you an actual module object,
here's what I use:

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

The only advantage (or maybe it is a disadvantage?) I can see to
your function is that it doesn't search the Python path and you can
specify an absolute file name.

Which is exactly what the OP asked for (though he didn't necessarily
need a module object).
I'm not arguing, you could very well be right, but I'm just curious what
part of the OP's post led you to believe he needed to specify an absolute
filename. Unless I'm missing a second post, he certainly never suggested
that his scripts weren't in the Python path, or that he couldn't add their
location to the path.

*shrug* It probably isn't important -- given the constraints as you read
them (extrapolated them?) your solution looks good.
--
Steven.

Oct 31 '06 #10
Steven D'Aprano wrote:
I'm not arguing, you could very well be right, but I'm just curious what
part of the OP's post led you to believe he needed to specify an absolute
filename. Unless I'm missing a second post, he certainly never suggested
that his scripts weren't in the Python path, or that he couldn't add their
location to the path.
the fact that he's using dashes in the module name might be a hint, though.

in current versions, __import__ doesn't care as long as the file has
the right extension, but import requires valid Python identifiers, for
obvious reasons.

execfile doesn't care about any part of the filename, of course (and if
you replace it with exec, you don't even have to read the script from a
file).

</F>

Oct 31 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: John F Dutcher | last post by:
Having 'cloned' an existing python script that imports 'string' and uses "string.rstrip()" without incident... I am at a loss to explain why the...
5
by: Steve Holden | last post by:
This is even stranger: it makes it if I import the module a second time: import dbimp as dbimp import sys if __name__ == "__main__":...
0
by: Bill Davy | last post by:
I am working with MSVC6 on Windows XP. I have created an MSVC project called SHIP I have a file SHIP.i with "%module SHIP" as the first line...
11
by: could ildg | last post by:
I want to import c:\xxx\yyy\zzz.py into my programme, What should I do? Thank you~
79
by: pinkfloydhomer | last post by:
I want to scan a file byte for byte for occurences of the the four byte pattern 0x00000100. I've tried with this: # start import sys numChars...
10
by: py | last post by:
I have a python script that I want to test/debug. It contains a class which extends from some other class which is located in some other python...
14
by: DataSmash | last post by:
Hi, When I import the random module at the python interpreter, it works fine: >>> import random >>> x = random.randint(1,55) >>> print x 14...
9
by: fegge | last post by:
i have written script save as hello.py. i can run it. but why cant i import it as a modular in other programs?
10
by: Jia Lu | last post by:
Hi all: I try to do things below: import i Traceback (most recent call last): File "<pyshell#67>", line 2, in <module> import i ImportError:...
1
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.