473,598 Members | 3,285 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2640
wrote in news:11******** **************@ i42g2000cwa.goo glegroups.com in
comp.lang.pytho n:
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***********@g mail.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(filena me, 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***********@g mail.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***********@g mail.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_fro m_file(module_n ame, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(modu le_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_fro m_file(module_n ame, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(modu le_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__("mat h")
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.T HIS.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_fro m_file(module_n ame, 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.T HIS.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_fro m_file(module_n ame, 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

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

Similar topics

0
1724
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 new 'cloned' script (brief sample below) continually errors with: NameError: global name 'string' is not defined args = ("global name 'string' is not defined",) when run from the server CGI-BIN. If the same script is run in 'IDLE' it
5
2466
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__": dbimp.install() #k = sys.modules.keys() #k.sort() #for kk in k:
0
2703
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 (file is below). I run SHIP.i through SWIG 1.3.24 to obtain SHIP_wrap.cpp and SHIP.py; the latter contains the line "import _SHIP". I compile SHIP_wrap.cpp and a bunch of files into a DLL which I have the
11
25045
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
5229
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 = 0 startCode = 0 count = 0
10
34353
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 file in a different directory. For example: c:\python_code\foo.py
14
9386
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 >>> BUT, when I put the same code in a python script:
9
382
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
2109
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: No module named i But it seems that import donot know what is i ? why?
0
7991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7902
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8395
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8398
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8050
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
5850
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3898
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1504
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1250
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.