Importing files other than *.py

E

Ed Leafe

If I have a Python script in a file named "burp.zz", is there any way
to import it into another script as you can with files named with the
..py extension?

I looked at the imp module, but was not able to make it do what I
wanted. Is this possible, or is the py/pyc extension required?

___/
/
__/
/
____/
Ed Leafe
http://leafe.com/
http://dabodev.com/
 
M

M.E.Farmer

Ed Leafe wrote in message:
If I have a Python script in a file named "burp.zz", is there any way
to import it into another script as you can with files named with the
.py extension?
I looked at the imp module, but was not able to make it do what I
wanted. Is this possible, or is the py/pyc extension required?
Ed Leafe
Hello Ed,
You can import as usuall if you do this:
Save this to your path.

# zz_import.py
import imputil

# define your custom file handler
def handle_zz(filepath, fileinfo, filename):
sourcefile = open(filepath, 'r')
data = sourcefile.read()
sourcefile.close()
return 0, compile(data, filepath, 'exec'),{}

importer = imputil.ImportManager()
importer.add_suffix('.zz', handle_zz)
importer.install()
# end zz_import.py

Now do this in your code:
import zz_import #now you can import zz files
import burp

If module is not found it will raise an ImportError.

HTH,
M.E.Famer
 
M

M.E.Farmer

Ed Leafe wrote in message:
If I have a Python script in a file named "burp.zz", is there any way
to import it into another script as you can with files named with the
.py extension?
I looked at the imp module, but was not able to make it do what I
wanted. Is this possible, or is the py/pyc extension required?
Ed Leafe
Hello Ed,
You can import as usuall if you do this:
Save this to your path.

# zz_import.py
import imputil

# define your custom file handler
def handle_zz(filepath, fileinfo, filename):
sourcefile = open(filepath, 'r')
data = sourcefile.read()
sourcefile.close()
return 0, compile(data, filepath, 'exec'),{}

importer = imputil.ImportManager()
importer.add_suffix('.zz', handle_zz)
importer.install()
# end zz_import.py

Now do this in your code:
import zz_import #now you can import zz files
import burp

If module is not found it will raise an ImportError.

HTH,
M.E.Farmer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top