LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Python: how to import a python file that doesn't end in .py? (http://www.linuxquestions.org/questions/programming-9/python-how-to-import-a-python-file-that-doesnt-end-in-py-635356/)

BrianK 04-14-2008 05:45 PM

Python: how to import a python file that doesn't end in .py?
 
Not sure if I'm overcomplicating things, but...

I need to import a python class that's defined in a file that does not end in .py (it has no extension). I'm guessing that the lack of .py extension is why I can't simply add the path and import.

Is there another way to import? Can I read the whole file into a var & exec that var? Is there some other way?

Thanks

ghostdog74 04-14-2008 08:18 PM

it not difficult to name it with a .py extension.

BrianK 04-14-2008 08:36 PM

Quote:

Originally Posted by ghostdog74 (Post 3121356)
it not difficult to name it with a .py extension.

::sigh:: really?

for anyone interested in how to actually solve this problem, here's what I've done:

Code:

mp4_script = 'path/to/python/script'
mp4file = file(mp4_script)
mp4mkr = mp4file.read()
mp4mkr = mp4mkr.replace("__main__","__absolutely_nothing__") # make sure we don't try to run it.
exec(mp4mkr)  # now we can use classes in this executable script just as if it were a module

... don't know if this is the "correct" way to importing a non-.py file, but it does the trick.

ntubski 04-14-2008 08:58 PM

You could use execfile (see http://docs.python.org/lib/built-in-funcs.html)

ghostdog74 04-15-2008 01:14 AM

Quote:

Originally Posted by BrianK (Post 3121371)
::sigh:: really?

Code:

# mv /path/to/python/script /path/to/python/lib/myscript.py
# python
Python 2.4.2
Type "help", "copyright", "credits" or "license" for more information.
>>> import myscript

or just simply move myscript to the python lib directory without renaming. It will still work.

BrianK 04-15-2008 12:35 PM

Quote:

Originally Posted by ghostdog74 (Post 3121554)
Code:

# mv /path/to/python/script /path/to/python/lib/myscript.py
# python
Python 2.4.2
Type "help", "copyright", "credits" or "license" for more information.
>>> import myscript

or just simply move myscript to the python lib directory without renaming. It will still work.

Thanks for the suggestion, but I don't own the file or directory, don't have write permissions where it lives, can't change the name because I'm not the only one/thing who uses it, and don't have write access to python's libdir.

I could copy it somewhere, yes. I could put a symbolic link somewhere, yes. Solutions like that, however, clutter up the file system with copies of files that could be used otherwise.



ntubski: thanks for execfile. that looks a little cleaner.


All times are GMT -5. The time now is 09:41 PM.